Deploy qwen2api-python (FastAPI gateway for chat.qwen.ai)
Browse filesThis view is limited to 50 files because it contains too many changes. See raw diff
- .dockerignore +69 -17
- .editorconfig +6 -0
- .env.example +22 -0
- .hfignore +0 -14
- Cargo.lock +0 -2410
- Cargo.toml +0 -27
- Dockerfile +78 -26
- README.md +1219 -137
- backend/__init__.py +1 -0
- backend/accounts.json +13 -0
- backend/adapter/__init__.py +1 -0
- backend/adapter/cli_proxy.py +258 -0
- backend/adapter/standard_request.py +38 -0
- backend/api/__init__.py +0 -0
- backend/api/admin.py +342 -0
- backend/api/anthropic.py +513 -0
- backend/api/embeddings.py +90 -0
- backend/api/files_api.py +77 -0
- backend/api/gemini.py +145 -0
- backend/api/images.py +599 -0
- backend/api/models.py +59 -0
- backend/api/probes.py +41 -0
- backend/api/v1_chat.py +235 -0
- backend/api/videos.py +652 -0
- backend/core/__init__.py +1 -0
- backend/core/account_pool/__init__.py +23 -0
- backend/core/account_pool/pool_acquire.py +252 -0
- backend/core/account_pool/pool_core.py +216 -0
- backend/core/account_pool_old.py +275 -0
- backend/core/browser_engine.py +58 -0
- backend/core/config.py +138 -0
- backend/core/database.py +48 -0
- backend/core/httpx_engine.py +135 -0
- backend/core/hybrid_engine.py +122 -0
- backend/core/log_filter.py +134 -0
- backend/core/request_logging.py +98 -0
- backend/core/session_affinity.py +153 -0
- backend/core/session_lock.py +40 -0
- backend/core/tool_cache.py +102 -0
- backend/core/upstream_file_cache.py +71 -0
- backend/main.py +139 -0
- backend/requirements.txt +10 -0
- backend/runtime/__init__.py +5 -0
- backend/runtime/attachment_types.py +19 -0
- backend/runtime/execution.py +1048 -0
- backend/runtime/stream_metrics.py +12 -0
- backend/runtime/stream_presenter.py +71 -0
- backend/runtime/stream_runtime.py +51 -0
- backend/services/attachment_preprocessor.py +138 -0
- backend/services/auth_quota.py +58 -0
.dockerignore
CHANGED
|
@@ -1,17 +1,69 @@
|
|
| 1 |
-
|
| 2 |
-
.
|
| 3 |
-
.
|
| 4 |
-
.
|
| 5 |
-
|
| 6 |
-
|
| 7 |
-
.env
|
| 8 |
-
|
| 9 |
-
.local
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# Git 相关
|
| 2 |
+
.git
|
| 3 |
+
.github
|
| 4 |
+
.gitignore
|
| 5 |
+
|
| 6 |
+
# 环境配置
|
| 7 |
+
.env
|
| 8 |
+
.env.local
|
| 9 |
+
.env.*.local
|
| 10 |
+
.venv
|
| 11 |
+
venv
|
| 12 |
+
env/
|
| 13 |
+
|
| 14 |
+
# Python 缓存
|
| 15 |
+
__pycache__/
|
| 16 |
+
**/__pycache__/
|
| 17 |
+
**/*.pyc
|
| 18 |
+
**/*.pyo
|
| 19 |
+
**/*.pyd
|
| 20 |
+
.Python
|
| 21 |
+
*.so
|
| 22 |
+
*.egg
|
| 23 |
+
*.egg-info/
|
| 24 |
+
dist/
|
| 25 |
+
build/
|
| 26 |
+
.pytest_cache/
|
| 27 |
+
.coverage
|
| 28 |
+
htmlcov/
|
| 29 |
+
|
| 30 |
+
# 日志和数据
|
| 31 |
+
*.log
|
| 32 |
+
data/
|
| 33 |
+
logs/
|
| 34 |
+
outputs/
|
| 35 |
+
temp/
|
| 36 |
+
tmp/
|
| 37 |
+
|
| 38 |
+
# 前端
|
| 39 |
+
frontend/node_modules/
|
| 40 |
+
frontend/dist/
|
| 41 |
+
frontend/.vite/
|
| 42 |
+
frontend/.turbo/
|
| 43 |
+
|
| 44 |
+
# IDE
|
| 45 |
+
.vscode/
|
| 46 |
+
.idea/
|
| 47 |
+
*.swp
|
| 48 |
+
*.swo
|
| 49 |
+
*~
|
| 50 |
+
.DS_Store
|
| 51 |
+
|
| 52 |
+
# 文档(构建时不需要)
|
| 53 |
+
*.md
|
| 54 |
+
!README.md
|
| 55 |
+
SESSION_*.md
|
| 56 |
+
FIX_*.md
|
| 57 |
+
QUICK_*.md
|
| 58 |
+
START_*.md
|
| 59 |
+
TOOL_*.md
|
| 60 |
+
|
| 61 |
+
# 测试文件
|
| 62 |
+
tests/
|
| 63 |
+
test_*.py
|
| 64 |
+
*_test.py
|
| 65 |
+
|
| 66 |
+
# 其他
|
| 67 |
+
.dockerignore
|
| 68 |
+
Dockerfile*
|
| 69 |
+
docker-compose*.yml
|
.editorconfig
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
root = true
|
| 2 |
+
|
| 3 |
+
[*]
|
| 4 |
+
indent_style = space
|
| 5 |
+
indent_size = 4
|
| 6 |
+
charset = utf-8
|
.env.example
ADDED
|
@@ -0,0 +1,22 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
ADMIN_KEY=change-me-now
|
| 2 |
+
PORT=7860
|
| 3 |
+
WORKERS=1
|
| 4 |
+
LOG_LEVEL=INFO
|
| 5 |
+
MAX_INFLIGHT=2
|
| 6 |
+
MAX_RETRIES=3
|
| 7 |
+
ACCOUNT_MIN_INTERVAL_MS=0
|
| 8 |
+
REQUEST_JITTER_MIN_MS=0
|
| 9 |
+
REQUEST_JITTER_MAX_MS=0
|
| 10 |
+
RATE_LIMIT_BASE_COOLDOWN=600
|
| 11 |
+
RATE_LIMIT_MAX_COOLDOWN=3600
|
| 12 |
+
ACCOUNTS_FILE=/workspace/data/accounts.json
|
| 13 |
+
USERS_FILE=/workspace/data/users.json
|
| 14 |
+
CAPTURES_FILE=/workspace/data/captures.json
|
| 15 |
+
CONTEXT_GENERATED_DIR=/workspace/data/context_files
|
| 16 |
+
CONTEXT_CACHE_FILE=/workspace/data/context_cache.json
|
| 17 |
+
UPLOADED_FILES_FILE=/workspace/data/uploaded_files.json
|
| 18 |
+
CONTEXT_AFFINITY_FILE=/workspace/data/session_affinity.json
|
| 19 |
+
CONTEXT_INLINE_MAX_CHARS=4000
|
| 20 |
+
CONTEXT_FORCE_FILE_MAX_CHARS=10000
|
| 21 |
+
CONTEXT_ATTACHMENT_TTL_SECONDS=1800
|
| 22 |
+
CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS=60
|
.hfignore
DELETED
|
@@ -1,14 +0,0 @@
|
|
| 1 |
-
.git/
|
| 2 |
-
.agents/
|
| 3 |
-
.codex/
|
| 4 |
-
.trellis/
|
| 5 |
-
.env
|
| 6 |
-
.env.*
|
| 7 |
-
target/
|
| 8 |
-
.local-postgres/
|
| 9 |
-
run-output/
|
| 10 |
-
run-logs/
|
| 11 |
-
linuxdo-auth-store.json
|
| 12 |
-
monitor/
|
| 13 |
-
AUDIT.md
|
| 14 |
-
AGENTS.md
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Cargo.lock
DELETED
|
@@ -1,2410 +0,0 @@
|
|
| 1 |
-
# This file is automatically @generated by Cargo.
|
| 2 |
-
# It is not intended for manual editing.
|
| 3 |
-
version = 4
|
| 4 |
-
|
| 5 |
-
[[package]]
|
| 6 |
-
name = "aho-corasick"
|
| 7 |
-
version = "1.1.4"
|
| 8 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 9 |
-
checksum = "ddd31a130427c27518df266943a5308ed92d4b226cc639f5a8f1002816174301"
|
| 10 |
-
dependencies = [
|
| 11 |
-
"memchr",
|
| 12 |
-
]
|
| 13 |
-
|
| 14 |
-
[[package]]
|
| 15 |
-
name = "allocator-api2"
|
| 16 |
-
version = "0.2.21"
|
| 17 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 18 |
-
checksum = "683d7910e743518b0e34f1186f92494becacb047c7b6bf616c96772180fef923"
|
| 19 |
-
|
| 20 |
-
[[package]]
|
| 21 |
-
name = "anstream"
|
| 22 |
-
version = "1.0.0"
|
| 23 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 24 |
-
checksum = "824a212faf96e9acacdbd09febd34438f8f711fb84e09a8916013cd7815ca28d"
|
| 25 |
-
dependencies = [
|
| 26 |
-
"anstyle",
|
| 27 |
-
"anstyle-parse",
|
| 28 |
-
"anstyle-query",
|
| 29 |
-
"anstyle-wincon",
|
| 30 |
-
"colorchoice",
|
| 31 |
-
"is_terminal_polyfill",
|
| 32 |
-
"utf8parse",
|
| 33 |
-
]
|
| 34 |
-
|
| 35 |
-
[[package]]
|
| 36 |
-
name = "anstyle"
|
| 37 |
-
version = "1.0.14"
|
| 38 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 39 |
-
checksum = "940b3a0ca603d1eade50a4846a2afffd5ef57a9feac2c0e2ec2e14f9ead76000"
|
| 40 |
-
|
| 41 |
-
[[package]]
|
| 42 |
-
name = "anstyle-parse"
|
| 43 |
-
version = "1.0.0"
|
| 44 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 45 |
-
checksum = "52ce7f38b242319f7cabaa6813055467063ecdc9d355bbb4ce0c68908cd8130e"
|
| 46 |
-
dependencies = [
|
| 47 |
-
"utf8parse",
|
| 48 |
-
]
|
| 49 |
-
|
| 50 |
-
[[package]]
|
| 51 |
-
name = "anstyle-query"
|
| 52 |
-
version = "1.1.5"
|
| 53 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 54 |
-
checksum = "40c48f72fd53cd289104fc64099abca73db4166ad86ea0b4341abe65af83dadc"
|
| 55 |
-
dependencies = [
|
| 56 |
-
"windows-sys 0.61.2",
|
| 57 |
-
]
|
| 58 |
-
|
| 59 |
-
[[package]]
|
| 60 |
-
name = "anstyle-wincon"
|
| 61 |
-
version = "3.0.11"
|
| 62 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 63 |
-
checksum = "291e6a250ff86cd4a820112fb8898808a366d8f9f58ce16d1f538353ad55747d"
|
| 64 |
-
dependencies = [
|
| 65 |
-
"anstyle",
|
| 66 |
-
"once_cell_polyfill",
|
| 67 |
-
"windows-sys 0.61.2",
|
| 68 |
-
]
|
| 69 |
-
|
| 70 |
-
[[package]]
|
| 71 |
-
name = "async-trait"
|
| 72 |
-
version = "0.1.89"
|
| 73 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 74 |
-
checksum = "9035ad2d096bed7955a320ee7e2230574d28fd3c3a0f186cbea1ff3c7eed5dbb"
|
| 75 |
-
dependencies = [
|
| 76 |
-
"proc-macro2",
|
| 77 |
-
"quote",
|
| 78 |
-
"syn",
|
| 79 |
-
]
|
| 80 |
-
|
| 81 |
-
[[package]]
|
| 82 |
-
name = "atoi"
|
| 83 |
-
version = "2.0.0"
|
| 84 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 85 |
-
checksum = "f28d99ec8bfea296261ca1af174f24225171fea9664ba9003cbebee704810528"
|
| 86 |
-
dependencies = [
|
| 87 |
-
"num-traits",
|
| 88 |
-
]
|
| 89 |
-
|
| 90 |
-
[[package]]
|
| 91 |
-
name = "atomic-waker"
|
| 92 |
-
version = "1.1.2"
|
| 93 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 94 |
-
checksum = "1505bd5d3d116872e7271a6d4e16d81d0c8570876c8de68093a09ac269d8aac0"
|
| 95 |
-
|
| 96 |
-
[[package]]
|
| 97 |
-
name = "autocfg"
|
| 98 |
-
version = "1.5.1"
|
| 99 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 100 |
-
checksum = "f2032f911046de80f0a198e0901378627c33f59ea0ac00e363d481118bd70a53"
|
| 101 |
-
|
| 102 |
-
[[package]]
|
| 103 |
-
name = "axum"
|
| 104 |
-
version = "0.8.9"
|
| 105 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 106 |
-
checksum = "31b698c5f9a010f6573133b09e0de5408834d0c82f8d7475a89fc1867a71cd90"
|
| 107 |
-
dependencies = [
|
| 108 |
-
"axum-core",
|
| 109 |
-
"bytes",
|
| 110 |
-
"form_urlencoded",
|
| 111 |
-
"futures-util",
|
| 112 |
-
"http",
|
| 113 |
-
"http-body",
|
| 114 |
-
"http-body-util",
|
| 115 |
-
"hyper",
|
| 116 |
-
"hyper-util",
|
| 117 |
-
"itoa",
|
| 118 |
-
"matchit",
|
| 119 |
-
"memchr",
|
| 120 |
-
"mime",
|
| 121 |
-
"percent-encoding",
|
| 122 |
-
"pin-project-lite",
|
| 123 |
-
"serde_core",
|
| 124 |
-
"serde_json",
|
| 125 |
-
"serde_path_to_error",
|
| 126 |
-
"serde_urlencoded",
|
| 127 |
-
"sync_wrapper",
|
| 128 |
-
"tokio",
|
| 129 |
-
"tower",
|
| 130 |
-
"tower-layer",
|
| 131 |
-
"tower-service",
|
| 132 |
-
"tracing",
|
| 133 |
-
]
|
| 134 |
-
|
| 135 |
-
[[package]]
|
| 136 |
-
name = "axum-core"
|
| 137 |
-
version = "0.5.6"
|
| 138 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 139 |
-
checksum = "08c78f31d7b1291f7ee735c1c6780ccde7785daae9a9206026862dab7d8792d1"
|
| 140 |
-
dependencies = [
|
| 141 |
-
"bytes",
|
| 142 |
-
"futures-core",
|
| 143 |
-
"http",
|
| 144 |
-
"http-body",
|
| 145 |
-
"http-body-util",
|
| 146 |
-
"mime",
|
| 147 |
-
"pin-project-lite",
|
| 148 |
-
"sync_wrapper",
|
| 149 |
-
"tower-layer",
|
| 150 |
-
"tower-service",
|
| 151 |
-
"tracing",
|
| 152 |
-
]
|
| 153 |
-
|
| 154 |
-
[[package]]
|
| 155 |
-
name = "base64"
|
| 156 |
-
version = "0.22.1"
|
| 157 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 158 |
-
checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6"
|
| 159 |
-
|
| 160 |
-
[[package]]
|
| 161 |
-
name = "bitflags"
|
| 162 |
-
version = "2.13.0"
|
| 163 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 164 |
-
checksum = "b4388bee8683e3d04af747c73422af53102d2bd24d9eadb6cbc100baef4b43f8"
|
| 165 |
-
|
| 166 |
-
[[package]]
|
| 167 |
-
name = "block-buffer"
|
| 168 |
-
version = "0.10.4"
|
| 169 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 170 |
-
checksum = "3078c7629b62d3f0439517fa394996acacc5cbc91c5a20d8c658e77abd503a71"
|
| 171 |
-
dependencies = [
|
| 172 |
-
"generic-array",
|
| 173 |
-
]
|
| 174 |
-
|
| 175 |
-
[[package]]
|
| 176 |
-
name = "bumpalo"
|
| 177 |
-
version = "3.20.3"
|
| 178 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 179 |
-
checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649"
|
| 180 |
-
|
| 181 |
-
[[package]]
|
| 182 |
-
name = "byteorder"
|
| 183 |
-
version = "1.5.0"
|
| 184 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 185 |
-
checksum = "1fd0f2584146f6f2ef48085050886acf353beff7305ebd1ae69500e27c67f64b"
|
| 186 |
-
|
| 187 |
-
[[package]]
|
| 188 |
-
name = "bytes"
|
| 189 |
-
version = "1.12.0"
|
| 190 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 191 |
-
checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593"
|
| 192 |
-
|
| 193 |
-
[[package]]
|
| 194 |
-
name = "cc"
|
| 195 |
-
version = "1.2.65"
|
| 196 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 197 |
-
checksum = "e228eec9be7c17ccb640b59b36a5cd805ea2a564a4c5e162c2f659fea30d3b96"
|
| 198 |
-
dependencies = [
|
| 199 |
-
"find-msvc-tools",
|
| 200 |
-
"shlex",
|
| 201 |
-
]
|
| 202 |
-
|
| 203 |
-
[[package]]
|
| 204 |
-
name = "cfg-if"
|
| 205 |
-
version = "1.0.4"
|
| 206 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 207 |
-
checksum = "9330f8b2ff13f34540b44e946ef35111825727b38d33286ef986142615121801"
|
| 208 |
-
|
| 209 |
-
[[package]]
|
| 210 |
-
name = "cfg_aliases"
|
| 211 |
-
version = "0.2.1"
|
| 212 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 213 |
-
checksum = "613afe47fcd5fac7ccf1db93babcb082c5994d996f20b8b159f2ad1658eb5724"
|
| 214 |
-
|
| 215 |
-
[[package]]
|
| 216 |
-
name = "clap"
|
| 217 |
-
version = "4.6.1"
|
| 218 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 219 |
-
checksum = "1ddb117e43bbf7dacf0a4190fef4d345b9bad68dfc649cb349e7d17d28428e51"
|
| 220 |
-
dependencies = [
|
| 221 |
-
"clap_builder",
|
| 222 |
-
"clap_derive",
|
| 223 |
-
]
|
| 224 |
-
|
| 225 |
-
[[package]]
|
| 226 |
-
name = "clap_builder"
|
| 227 |
-
version = "4.6.0"
|
| 228 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 229 |
-
checksum = "714a53001bf66416adb0e2ef5ac857140e7dc3a0c48fb28b2f10762fc4b5069f"
|
| 230 |
-
dependencies = [
|
| 231 |
-
"anstream",
|
| 232 |
-
"anstyle",
|
| 233 |
-
"clap_lex",
|
| 234 |
-
"strsim",
|
| 235 |
-
]
|
| 236 |
-
|
| 237 |
-
[[package]]
|
| 238 |
-
name = "clap_derive"
|
| 239 |
-
version = "4.6.1"
|
| 240 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 241 |
-
checksum = "f2ce8604710f6733aa641a2b3731eaa1e8b3d9973d5e3565da11800813f997a9"
|
| 242 |
-
dependencies = [
|
| 243 |
-
"heck",
|
| 244 |
-
"proc-macro2",
|
| 245 |
-
"quote",
|
| 246 |
-
"syn",
|
| 247 |
-
]
|
| 248 |
-
|
| 249 |
-
[[package]]
|
| 250 |
-
name = "clap_lex"
|
| 251 |
-
version = "1.1.0"
|
| 252 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 253 |
-
checksum = "c8d4a3bb8b1e0c1050499d1815f5ab16d04f0959b233085fb31653fbfc9d98f9"
|
| 254 |
-
|
| 255 |
-
[[package]]
|
| 256 |
-
name = "colorchoice"
|
| 257 |
-
version = "1.0.5"
|
| 258 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 259 |
-
checksum = "1d07550c9036bf2ae0c684c4297d503f838287c83c53686d05370d0e139ae570"
|
| 260 |
-
|
| 261 |
-
[[package]]
|
| 262 |
-
name = "concurrent-queue"
|
| 263 |
-
version = "2.5.0"
|
| 264 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 265 |
-
checksum = "4ca0197aee26d1ae37445ee532fefce43251d24cc7c166799f4d46817f1d3973"
|
| 266 |
-
dependencies = [
|
| 267 |
-
"crossbeam-utils",
|
| 268 |
-
]
|
| 269 |
-
|
| 270 |
-
[[package]]
|
| 271 |
-
name = "cpufeatures"
|
| 272 |
-
version = "0.2.17"
|
| 273 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 274 |
-
checksum = "59ed5838eebb26a2bb2e58f6d5b5316989ae9d08bab10e0e6d103e656d1b0280"
|
| 275 |
-
dependencies = [
|
| 276 |
-
"libc",
|
| 277 |
-
]
|
| 278 |
-
|
| 279 |
-
[[package]]
|
| 280 |
-
name = "crc"
|
| 281 |
-
version = "3.4.0"
|
| 282 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 283 |
-
checksum = "5eb8a2a1cd12ab0d987a5d5e825195d372001a4094a0376319d5a0ad71c1ba0d"
|
| 284 |
-
dependencies = [
|
| 285 |
-
"crc-catalog",
|
| 286 |
-
]
|
| 287 |
-
|
| 288 |
-
[[package]]
|
| 289 |
-
name = "crc-catalog"
|
| 290 |
-
version = "2.5.0"
|
| 291 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 292 |
-
checksum = "217698eaf96b4a3f0bc4f3662aaa55bdf913cd54d7204591faa790070c6d0853"
|
| 293 |
-
|
| 294 |
-
[[package]]
|
| 295 |
-
name = "crossbeam-queue"
|
| 296 |
-
version = "0.3.12"
|
| 297 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 298 |
-
checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115"
|
| 299 |
-
dependencies = [
|
| 300 |
-
"crossbeam-utils",
|
| 301 |
-
]
|
| 302 |
-
|
| 303 |
-
[[package]]
|
| 304 |
-
name = "crossbeam-utils"
|
| 305 |
-
version = "0.8.21"
|
| 306 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 307 |
-
checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28"
|
| 308 |
-
|
| 309 |
-
[[package]]
|
| 310 |
-
name = "crypto-common"
|
| 311 |
-
version = "0.1.7"
|
| 312 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 313 |
-
checksum = "78c8292055d1c1df0cce5d180393dc8cce0abec0a7102adb6c7b1eef6016d60a"
|
| 314 |
-
dependencies = [
|
| 315 |
-
"generic-array",
|
| 316 |
-
"typenum",
|
| 317 |
-
]
|
| 318 |
-
|
| 319 |
-
[[package]]
|
| 320 |
-
name = "digest"
|
| 321 |
-
version = "0.10.7"
|
| 322 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 323 |
-
checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292"
|
| 324 |
-
dependencies = [
|
| 325 |
-
"block-buffer",
|
| 326 |
-
"crypto-common",
|
| 327 |
-
"subtle",
|
| 328 |
-
]
|
| 329 |
-
|
| 330 |
-
[[package]]
|
| 331 |
-
name = "displaydoc"
|
| 332 |
-
version = "0.2.6"
|
| 333 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 334 |
-
checksum = "1ac70aa55017e108007fbaf5aa0f54b021c98f92ff8af59d42eda9da96e3dd4f"
|
| 335 |
-
dependencies = [
|
| 336 |
-
"proc-macro2",
|
| 337 |
-
"quote",
|
| 338 |
-
"syn",
|
| 339 |
-
]
|
| 340 |
-
|
| 341 |
-
[[package]]
|
| 342 |
-
name = "dotenvy"
|
| 343 |
-
version = "0.15.7"
|
| 344 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 345 |
-
checksum = "1aaf95b3e5c8f23aa320147307562d361db0ae0d51242340f558153b4eb2439b"
|
| 346 |
-
|
| 347 |
-
[[package]]
|
| 348 |
-
name = "either"
|
| 349 |
-
version = "1.16.0"
|
| 350 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 351 |
-
checksum = "91622ff5e7162018101f2fea40d6ebf4a78bbe5a49736a2020649edf9693679e"
|
| 352 |
-
dependencies = [
|
| 353 |
-
"serde",
|
| 354 |
-
]
|
| 355 |
-
|
| 356 |
-
[[package]]
|
| 357 |
-
name = "equivalent"
|
| 358 |
-
version = "1.0.2"
|
| 359 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 360 |
-
checksum = "877a4ace8713b0bcf2a4e7eec82529c029f1d0619886d18145fea96c3ffe5c0f"
|
| 361 |
-
|
| 362 |
-
[[package]]
|
| 363 |
-
name = "errno"
|
| 364 |
-
version = "0.3.14"
|
| 365 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 366 |
-
checksum = "39cab71617ae0d63f51a36d69f866391735b51691dbda63cf6f96d042b63efeb"
|
| 367 |
-
dependencies = [
|
| 368 |
-
"libc",
|
| 369 |
-
"windows-sys 0.61.2",
|
| 370 |
-
]
|
| 371 |
-
|
| 372 |
-
[[package]]
|
| 373 |
-
name = "etcetera"
|
| 374 |
-
version = "0.8.0"
|
| 375 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 376 |
-
checksum = "136d1b5283a1ab77bd9257427ffd09d8667ced0570b6f938942bc7568ed5b943"
|
| 377 |
-
dependencies = [
|
| 378 |
-
"cfg-if",
|
| 379 |
-
"home",
|
| 380 |
-
"windows-sys 0.48.0",
|
| 381 |
-
]
|
| 382 |
-
|
| 383 |
-
[[package]]
|
| 384 |
-
name = "event-listener"
|
| 385 |
-
version = "5.4.1"
|
| 386 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 387 |
-
checksum = "e13b66accf52311f30a0db42147dadea9850cb48cd070028831ae5f5d4b856ab"
|
| 388 |
-
dependencies = [
|
| 389 |
-
"concurrent-queue",
|
| 390 |
-
"parking",
|
| 391 |
-
"pin-project-lite",
|
| 392 |
-
]
|
| 393 |
-
|
| 394 |
-
[[package]]
|
| 395 |
-
name = "fastrand"
|
| 396 |
-
version = "2.4.1"
|
| 397 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 398 |
-
checksum = "9f1f227452a390804cdb637b74a86990f2a7d7ba4b7d5693aac9b4dd6defd8d6"
|
| 399 |
-
|
| 400 |
-
[[package]]
|
| 401 |
-
name = "find-msvc-tools"
|
| 402 |
-
version = "0.1.9"
|
| 403 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 404 |
-
checksum = "5baebc0774151f905a1a2cc41989300b1e6fbb29aff0ceffa1064fdd3088d582"
|
| 405 |
-
|
| 406 |
-
[[package]]
|
| 407 |
-
name = "foldhash"
|
| 408 |
-
version = "0.1.5"
|
| 409 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 410 |
-
checksum = "d9c4f5dac5e15c24eb999c26181a6ca40b39fe946cbe4c263c7209467bc83af2"
|
| 411 |
-
|
| 412 |
-
[[package]]
|
| 413 |
-
name = "form_urlencoded"
|
| 414 |
-
version = "1.2.2"
|
| 415 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 416 |
-
checksum = "cb4cb245038516f5f85277875cdaa4f7d2c9a0fa0468de06ed190163b1581fcf"
|
| 417 |
-
dependencies = [
|
| 418 |
-
"percent-encoding",
|
| 419 |
-
]
|
| 420 |
-
|
| 421 |
-
[[package]]
|
| 422 |
-
name = "futures-channel"
|
| 423 |
-
version = "0.3.32"
|
| 424 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 425 |
-
checksum = "07bbe89c50d7a535e539b8c17bc0b49bdb77747034daa8087407d655f3f7cc1d"
|
| 426 |
-
dependencies = [
|
| 427 |
-
"futures-core",
|
| 428 |
-
"futures-sink",
|
| 429 |
-
]
|
| 430 |
-
|
| 431 |
-
[[package]]
|
| 432 |
-
name = "futures-core"
|
| 433 |
-
version = "0.3.32"
|
| 434 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 435 |
-
checksum = "7e3450815272ef58cec6d564423f6e755e25379b217b0bc688e295ba24df6b1d"
|
| 436 |
-
|
| 437 |
-
[[package]]
|
| 438 |
-
name = "futures-intrusive"
|
| 439 |
-
version = "0.5.0"
|
| 440 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 441 |
-
checksum = "1d930c203dd0b6ff06e0201a4a2fe9149b43c684fd4420555b26d21b1a02956f"
|
| 442 |
-
dependencies = [
|
| 443 |
-
"futures-core",
|
| 444 |
-
"lock_api",
|
| 445 |
-
"parking_lot",
|
| 446 |
-
]
|
| 447 |
-
|
| 448 |
-
[[package]]
|
| 449 |
-
name = "futures-io"
|
| 450 |
-
version = "0.3.32"
|
| 451 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 452 |
-
checksum = "cecba35d7ad927e23624b22ad55235f2239cfa44fd10428eecbeba6d6a717718"
|
| 453 |
-
|
| 454 |
-
[[package]]
|
| 455 |
-
name = "futures-sink"
|
| 456 |
-
version = "0.3.32"
|
| 457 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 458 |
-
checksum = "c39754e157331b013978ec91992bde1ac089843443c49cbc7f46150b0fad0893"
|
| 459 |
-
|
| 460 |
-
[[package]]
|
| 461 |
-
name = "futures-task"
|
| 462 |
-
version = "0.3.32"
|
| 463 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 464 |
-
checksum = "037711b3d59c33004d3856fbdc83b99d4ff37a24768fa1be9ce3538a1cde4393"
|
| 465 |
-
|
| 466 |
-
[[package]]
|
| 467 |
-
name = "futures-util"
|
| 468 |
-
version = "0.3.32"
|
| 469 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 470 |
-
checksum = "389ca41296e6190b48053de0321d02a77f32f8a5d2461dd38762c0593805c6d6"
|
| 471 |
-
dependencies = [
|
| 472 |
-
"futures-core",
|
| 473 |
-
"futures-io",
|
| 474 |
-
"futures-sink",
|
| 475 |
-
"futures-task",
|
| 476 |
-
"memchr",
|
| 477 |
-
"pin-project-lite",
|
| 478 |
-
"slab",
|
| 479 |
-
]
|
| 480 |
-
|
| 481 |
-
[[package]]
|
| 482 |
-
name = "generic-array"
|
| 483 |
-
version = "0.14.7"
|
| 484 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 485 |
-
checksum = "85649ca51fd72272d7821adaf274ad91c288277713d9c18820d8499a7ff69e9a"
|
| 486 |
-
dependencies = [
|
| 487 |
-
"typenum",
|
| 488 |
-
"version_check",
|
| 489 |
-
]
|
| 490 |
-
|
| 491 |
-
[[package]]
|
| 492 |
-
name = "getrandom"
|
| 493 |
-
version = "0.2.17"
|
| 494 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 495 |
-
checksum = "ff2abc00be7fca6ebc474524697ae276ad847ad0a6b3faa4bcb027e9a4614ad0"
|
| 496 |
-
dependencies = [
|
| 497 |
-
"cfg-if",
|
| 498 |
-
"js-sys",
|
| 499 |
-
"libc",
|
| 500 |
-
"wasi",
|
| 501 |
-
"wasm-bindgen",
|
| 502 |
-
]
|
| 503 |
-
|
| 504 |
-
[[package]]
|
| 505 |
-
name = "getrandom"
|
| 506 |
-
version = "0.3.4"
|
| 507 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 508 |
-
checksum = "899def5c37c4fd7b2664648c28120ecec138e4d395b459e5ca34f9cce2dd77fd"
|
| 509 |
-
dependencies = [
|
| 510 |
-
"cfg-if",
|
| 511 |
-
"js-sys",
|
| 512 |
-
"libc",
|
| 513 |
-
"r-efi 5.3.0",
|
| 514 |
-
"wasip2",
|
| 515 |
-
"wasm-bindgen",
|
| 516 |
-
]
|
| 517 |
-
|
| 518 |
-
[[package]]
|
| 519 |
-
name = "getrandom"
|
| 520 |
-
version = "0.4.3"
|
| 521 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 522 |
-
checksum = "300e883d756b2e4ec94e02791f39b04b522276138852cfc41d9fb7e904106099"
|
| 523 |
-
dependencies = [
|
| 524 |
-
"cfg-if",
|
| 525 |
-
"libc",
|
| 526 |
-
"r-efi 6.0.0",
|
| 527 |
-
]
|
| 528 |
-
|
| 529 |
-
[[package]]
|
| 530 |
-
name = "hashbrown"
|
| 531 |
-
version = "0.15.5"
|
| 532 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 533 |
-
checksum = "9229cfe53dfd69f0609a49f65461bd93001ea1ef889cd5529dd176593f5338a1"
|
| 534 |
-
dependencies = [
|
| 535 |
-
"allocator-api2",
|
| 536 |
-
"equivalent",
|
| 537 |
-
"foldhash",
|
| 538 |
-
]
|
| 539 |
-
|
| 540 |
-
[[package]]
|
| 541 |
-
name = "hashbrown"
|
| 542 |
-
version = "0.17.1"
|
| 543 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 544 |
-
checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a"
|
| 545 |
-
|
| 546 |
-
[[package]]
|
| 547 |
-
name = "hashlink"
|
| 548 |
-
version = "0.10.0"
|
| 549 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 550 |
-
checksum = "7382cf6263419f2d8df38c55d7da83da5c18aef87fc7a7fc1fb1e344edfe14c1"
|
| 551 |
-
dependencies = [
|
| 552 |
-
"hashbrown 0.15.5",
|
| 553 |
-
]
|
| 554 |
-
|
| 555 |
-
[[package]]
|
| 556 |
-
name = "heck"
|
| 557 |
-
version = "0.5.0"
|
| 558 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 559 |
-
checksum = "2304e00983f87ffb38b55b444b5e3b60a884b5d30c0fca7d82fe33449bbe55ea"
|
| 560 |
-
|
| 561 |
-
[[package]]
|
| 562 |
-
name = "hex"
|
| 563 |
-
version = "0.4.3"
|
| 564 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 565 |
-
checksum = "7f24254aa9a54b5c858eaee2f5bccdb46aaf0e486a595ed5fd8f86ba55232a70"
|
| 566 |
-
|
| 567 |
-
[[package]]
|
| 568 |
-
name = "hkdf"
|
| 569 |
-
version = "0.12.4"
|
| 570 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 571 |
-
checksum = "7b5f8eb2ad728638ea2c7d47a21db23b7b58a72ed6a38256b8a1849f15fbbdf7"
|
| 572 |
-
dependencies = [
|
| 573 |
-
"hmac",
|
| 574 |
-
]
|
| 575 |
-
|
| 576 |
-
[[package]]
|
| 577 |
-
name = "hmac"
|
| 578 |
-
version = "0.12.1"
|
| 579 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 580 |
-
checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e"
|
| 581 |
-
dependencies = [
|
| 582 |
-
"digest",
|
| 583 |
-
]
|
| 584 |
-
|
| 585 |
-
[[package]]
|
| 586 |
-
name = "home"
|
| 587 |
-
version = "0.5.12"
|
| 588 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 589 |
-
checksum = "cc627f471c528ff0c4a49e1d5e60450c8f6461dd6d10ba9dcd3a61d3dff7728d"
|
| 590 |
-
dependencies = [
|
| 591 |
-
"windows-sys 0.61.2",
|
| 592 |
-
]
|
| 593 |
-
|
| 594 |
-
[[package]]
|
| 595 |
-
name = "http"
|
| 596 |
-
version = "1.4.2"
|
| 597 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 598 |
-
checksum = "6970f50e31d6fc17d3fa27329444bfa74e196cf62e95052a3f6fee181dba6425"
|
| 599 |
-
dependencies = [
|
| 600 |
-
"bytes",
|
| 601 |
-
"itoa",
|
| 602 |
-
]
|
| 603 |
-
|
| 604 |
-
[[package]]
|
| 605 |
-
name = "http-body"
|
| 606 |
-
version = "1.0.1"
|
| 607 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 608 |
-
checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184"
|
| 609 |
-
dependencies = [
|
| 610 |
-
"bytes",
|
| 611 |
-
"http",
|
| 612 |
-
]
|
| 613 |
-
|
| 614 |
-
[[package]]
|
| 615 |
-
name = "http-body-util"
|
| 616 |
-
version = "0.1.3"
|
| 617 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 618 |
-
checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a"
|
| 619 |
-
dependencies = [
|
| 620 |
-
"bytes",
|
| 621 |
-
"futures-core",
|
| 622 |
-
"http",
|
| 623 |
-
"http-body",
|
| 624 |
-
"pin-project-lite",
|
| 625 |
-
]
|
| 626 |
-
|
| 627 |
-
[[package]]
|
| 628 |
-
name = "httparse"
|
| 629 |
-
version = "1.10.1"
|
| 630 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 631 |
-
checksum = "6dbf3de79e51f3d586ab4cb9d5c3e2c14aa28ed23d180cf89b4df0454a69cc87"
|
| 632 |
-
|
| 633 |
-
[[package]]
|
| 634 |
-
name = "httpdate"
|
| 635 |
-
version = "1.0.3"
|
| 636 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 637 |
-
checksum = "df3b46402a9d5adb4c86a0cf463f42e19994e3ee891101b1841f30a545cb49a9"
|
| 638 |
-
|
| 639 |
-
[[package]]
|
| 640 |
-
name = "hyper"
|
| 641 |
-
version = "1.10.1"
|
| 642 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 643 |
-
checksum = "55281c53a1894c864990125767da440a4e630446785086f52523b20033b74498"
|
| 644 |
-
dependencies = [
|
| 645 |
-
"atomic-waker",
|
| 646 |
-
"bytes",
|
| 647 |
-
"futures-channel",
|
| 648 |
-
"futures-core",
|
| 649 |
-
"http",
|
| 650 |
-
"http-body",
|
| 651 |
-
"httparse",
|
| 652 |
-
"httpdate",
|
| 653 |
-
"itoa",
|
| 654 |
-
"pin-project-lite",
|
| 655 |
-
"smallvec",
|
| 656 |
-
"tokio",
|
| 657 |
-
"want",
|
| 658 |
-
]
|
| 659 |
-
|
| 660 |
-
[[package]]
|
| 661 |
-
name = "hyper-rustls"
|
| 662 |
-
version = "0.27.9"
|
| 663 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 664 |
-
checksum = "33ca68d021ef39cf6463ab54c1d0f5daf03377b70561305bb89a8f83aab66e0f"
|
| 665 |
-
dependencies = [
|
| 666 |
-
"http",
|
| 667 |
-
"hyper",
|
| 668 |
-
"hyper-util",
|
| 669 |
-
"rustls",
|
| 670 |
-
"tokio",
|
| 671 |
-
"tokio-rustls",
|
| 672 |
-
"tower-service",
|
| 673 |
-
"webpki-roots 1.0.8",
|
| 674 |
-
]
|
| 675 |
-
|
| 676 |
-
[[package]]
|
| 677 |
-
name = "hyper-util"
|
| 678 |
-
version = "0.1.20"
|
| 679 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 680 |
-
checksum = "96547c2556ec9d12fb1578c4eaf448b04993e7fb79cbaad930a656880a6bdfa0"
|
| 681 |
-
dependencies = [
|
| 682 |
-
"base64",
|
| 683 |
-
"bytes",
|
| 684 |
-
"futures-channel",
|
| 685 |
-
"futures-util",
|
| 686 |
-
"http",
|
| 687 |
-
"http-body",
|
| 688 |
-
"hyper",
|
| 689 |
-
"ipnet",
|
| 690 |
-
"libc",
|
| 691 |
-
"percent-encoding",
|
| 692 |
-
"pin-project-lite",
|
| 693 |
-
"socket2",
|
| 694 |
-
"tokio",
|
| 695 |
-
"tower-service",
|
| 696 |
-
"tracing",
|
| 697 |
-
]
|
| 698 |
-
|
| 699 |
-
[[package]]
|
| 700 |
-
name = "icu_collections"
|
| 701 |
-
version = "2.2.0"
|
| 702 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 703 |
-
checksum = "2984d1cd16c883d7935b9e07e44071dca8d917fd52ecc02c04d5fa0b5a3f191c"
|
| 704 |
-
dependencies = [
|
| 705 |
-
"displaydoc",
|
| 706 |
-
"potential_utf",
|
| 707 |
-
"utf8_iter",
|
| 708 |
-
"yoke",
|
| 709 |
-
"zerofrom",
|
| 710 |
-
"zerovec",
|
| 711 |
-
]
|
| 712 |
-
|
| 713 |
-
[[package]]
|
| 714 |
-
name = "icu_locale_core"
|
| 715 |
-
version = "2.2.0"
|
| 716 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 717 |
-
checksum = "92219b62b3e2b4d88ac5119f8904c10f8f61bf7e95b640d25ba3075e6cac2c29"
|
| 718 |
-
dependencies = [
|
| 719 |
-
"displaydoc",
|
| 720 |
-
"litemap",
|
| 721 |
-
"tinystr",
|
| 722 |
-
"writeable",
|
| 723 |
-
"zerovec",
|
| 724 |
-
]
|
| 725 |
-
|
| 726 |
-
[[package]]
|
| 727 |
-
name = "icu_normalizer"
|
| 728 |
-
version = "2.2.0"
|
| 729 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 730 |
-
checksum = "c56e5ee99d6e3d33bd91c5d85458b6005a22140021cc324cea84dd0e72cff3b4"
|
| 731 |
-
dependencies = [
|
| 732 |
-
"icu_collections",
|
| 733 |
-
"icu_normalizer_data",
|
| 734 |
-
"icu_properties",
|
| 735 |
-
"icu_provider",
|
| 736 |
-
"smallvec",
|
| 737 |
-
"zerovec",
|
| 738 |
-
]
|
| 739 |
-
|
| 740 |
-
[[package]]
|
| 741 |
-
name = "icu_normalizer_data"
|
| 742 |
-
version = "2.2.0"
|
| 743 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 744 |
-
checksum = "da3be0ae77ea334f4da67c12f149704f19f81d1adf7c51cf482943e84a2bad38"
|
| 745 |
-
|
| 746 |
-
[[package]]
|
| 747 |
-
name = "icu_properties"
|
| 748 |
-
version = "2.2.0"
|
| 749 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 750 |
-
checksum = "bee3b67d0ea5c2cca5003417989af8996f8604e34fb9ddf96208a033901e70de"
|
| 751 |
-
dependencies = [
|
| 752 |
-
"icu_collections",
|
| 753 |
-
"icu_locale_core",
|
| 754 |
-
"icu_properties_data",
|
| 755 |
-
"icu_provider",
|
| 756 |
-
"zerotrie",
|
| 757 |
-
"zerovec",
|
| 758 |
-
]
|
| 759 |
-
|
| 760 |
-
[[package]]
|
| 761 |
-
name = "icu_properties_data"
|
| 762 |
-
version = "2.2.0"
|
| 763 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 764 |
-
checksum = "8e2bbb201e0c04f7b4b3e14382af113e17ba4f63e2c9d2ee626b720cbce54a14"
|
| 765 |
-
|
| 766 |
-
[[package]]
|
| 767 |
-
name = "icu_provider"
|
| 768 |
-
version = "2.2.0"
|
| 769 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 770 |
-
checksum = "139c4cf31c8b5f33d7e199446eff9c1e02decfc2f0eec2c8d71f65befa45b421"
|
| 771 |
-
dependencies = [
|
| 772 |
-
"displaydoc",
|
| 773 |
-
"icu_locale_core",
|
| 774 |
-
"writeable",
|
| 775 |
-
"yoke",
|
| 776 |
-
"zerofrom",
|
| 777 |
-
"zerotrie",
|
| 778 |
-
"zerovec",
|
| 779 |
-
]
|
| 780 |
-
|
| 781 |
-
[[package]]
|
| 782 |
-
name = "ideal-link-extractor-rust"
|
| 783 |
-
version = "0.1.0"
|
| 784 |
-
dependencies = [
|
| 785 |
-
"async-trait",
|
| 786 |
-
"axum",
|
| 787 |
-
"base64",
|
| 788 |
-
"clap",
|
| 789 |
-
"regex",
|
| 790 |
-
"reqwest",
|
| 791 |
-
"serde",
|
| 792 |
-
"serde_json",
|
| 793 |
-
"sqlx",
|
| 794 |
-
"tempfile",
|
| 795 |
-
"thiserror 1.0.69",
|
| 796 |
-
"tokio",
|
| 797 |
-
"url",
|
| 798 |
-
"uuid",
|
| 799 |
-
]
|
| 800 |
-
|
| 801 |
-
[[package]]
|
| 802 |
-
name = "idna"
|
| 803 |
-
version = "1.1.0"
|
| 804 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 805 |
-
checksum = "3b0875f23caa03898994f6ddc501886a45c7d3d62d04d2d90788d47be1b1e4de"
|
| 806 |
-
dependencies = [
|
| 807 |
-
"idna_adapter",
|
| 808 |
-
"smallvec",
|
| 809 |
-
"utf8_iter",
|
| 810 |
-
]
|
| 811 |
-
|
| 812 |
-
[[package]]
|
| 813 |
-
name = "idna_adapter"
|
| 814 |
-
version = "1.2.2"
|
| 815 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 816 |
-
checksum = "cb68373c0d6620ef8105e855e7745e18b0d00d3bdb07fb532e434244cdb9a714"
|
| 817 |
-
dependencies = [
|
| 818 |
-
"icu_normalizer",
|
| 819 |
-
"icu_properties",
|
| 820 |
-
]
|
| 821 |
-
|
| 822 |
-
[[package]]
|
| 823 |
-
name = "indexmap"
|
| 824 |
-
version = "2.14.0"
|
| 825 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 826 |
-
checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9"
|
| 827 |
-
dependencies = [
|
| 828 |
-
"equivalent",
|
| 829 |
-
"hashbrown 0.17.1",
|
| 830 |
-
]
|
| 831 |
-
|
| 832 |
-
[[package]]
|
| 833 |
-
name = "ipnet"
|
| 834 |
-
version = "2.12.0"
|
| 835 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 836 |
-
checksum = "d98f6fed1fde3f8c21bc40a1abb88dd75e67924f9cffc3ef95607bad8017f8e2"
|
| 837 |
-
|
| 838 |
-
[[package]]
|
| 839 |
-
name = "is_terminal_polyfill"
|
| 840 |
-
version = "1.70.2"
|
| 841 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 842 |
-
checksum = "a6cb138bb79a146c1bd460005623e142ef0181e3d0219cb493e02f7d08a35695"
|
| 843 |
-
|
| 844 |
-
[[package]]
|
| 845 |
-
name = "itoa"
|
| 846 |
-
version = "1.0.18"
|
| 847 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 848 |
-
checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682"
|
| 849 |
-
|
| 850 |
-
[[package]]
|
| 851 |
-
name = "js-sys"
|
| 852 |
-
version = "0.3.103"
|
| 853 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 854 |
-
checksum = "53b44bfcdb3f8d5837a46dae1ca9660a837176eee74a28b229bc626816589102"
|
| 855 |
-
dependencies = [
|
| 856 |
-
"cfg-if",
|
| 857 |
-
"futures-util",
|
| 858 |
-
"wasm-bindgen",
|
| 859 |
-
]
|
| 860 |
-
|
| 861 |
-
[[package]]
|
| 862 |
-
name = "libc"
|
| 863 |
-
version = "0.2.186"
|
| 864 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 865 |
-
checksum = "68ab91017fe16c622486840e4c83c9a37afeff978bd239b5293d61ece587de66"
|
| 866 |
-
|
| 867 |
-
[[package]]
|
| 868 |
-
name = "libredox"
|
| 869 |
-
version = "0.1.18"
|
| 870 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 871 |
-
checksum = "c943259e342f1e06ff2da7a83eabdfe7f92ce10262688dbf1895ff0b3e6e4652"
|
| 872 |
-
dependencies = [
|
| 873 |
-
"bitflags",
|
| 874 |
-
"libc",
|
| 875 |
-
"plain",
|
| 876 |
-
"redox_syscall 0.9.0",
|
| 877 |
-
]
|
| 878 |
-
|
| 879 |
-
[[package]]
|
| 880 |
-
name = "linux-raw-sys"
|
| 881 |
-
version = "0.12.1"
|
| 882 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 883 |
-
checksum = "32a66949e030da00e8c7d4434b251670a91556f4144941d37452769c25d58a53"
|
| 884 |
-
|
| 885 |
-
[[package]]
|
| 886 |
-
name = "litemap"
|
| 887 |
-
version = "0.8.2"
|
| 888 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 889 |
-
checksum = "92daf443525c4cce67b150400bc2316076100ce0b3686209eb8cf3c31612e6f0"
|
| 890 |
-
|
| 891 |
-
[[package]]
|
| 892 |
-
name = "lock_api"
|
| 893 |
-
version = "0.4.14"
|
| 894 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 895 |
-
checksum = "224399e74b87b5f3557511d98dff8b14089b3dadafcab6bb93eab67d3aace965"
|
| 896 |
-
dependencies = [
|
| 897 |
-
"scopeguard",
|
| 898 |
-
]
|
| 899 |
-
|
| 900 |
-
[[package]]
|
| 901 |
-
name = "log"
|
| 902 |
-
version = "0.4.33"
|
| 903 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 904 |
-
checksum = "0ceec5bc11778974d1bcb055b18002eba7f4b3518b6a0081b3af5f21666da9ad"
|
| 905 |
-
|
| 906 |
-
[[package]]
|
| 907 |
-
name = "lru-slab"
|
| 908 |
-
version = "0.1.2"
|
| 909 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 910 |
-
checksum = "112b39cec0b298b6c1999fee3e31427f74f676e4cb9879ed1a121b43661a4154"
|
| 911 |
-
|
| 912 |
-
[[package]]
|
| 913 |
-
name = "matchit"
|
| 914 |
-
version = "0.8.4"
|
| 915 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 916 |
-
checksum = "47e1ffaa40ddd1f3ed91f717a33c8c0ee23fff369e3aa8772b9605cc1d22f4c3"
|
| 917 |
-
|
| 918 |
-
[[package]]
|
| 919 |
-
name = "md-5"
|
| 920 |
-
version = "0.10.6"
|
| 921 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 922 |
-
checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf"
|
| 923 |
-
dependencies = [
|
| 924 |
-
"cfg-if",
|
| 925 |
-
"digest",
|
| 926 |
-
]
|
| 927 |
-
|
| 928 |
-
[[package]]
|
| 929 |
-
name = "memchr"
|
| 930 |
-
version = "2.8.2"
|
| 931 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 932 |
-
checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4"
|
| 933 |
-
|
| 934 |
-
[[package]]
|
| 935 |
-
name = "mime"
|
| 936 |
-
version = "0.3.17"
|
| 937 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 938 |
-
checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a"
|
| 939 |
-
|
| 940 |
-
[[package]]
|
| 941 |
-
name = "mio"
|
| 942 |
-
version = "1.2.1"
|
| 943 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 944 |
-
checksum = "02bd0af71c67b473010cbbc60715ee815645a4dc942899111f494b4b737d6fda"
|
| 945 |
-
dependencies = [
|
| 946 |
-
"libc",
|
| 947 |
-
"wasi",
|
| 948 |
-
"windows-sys 0.61.2",
|
| 949 |
-
]
|
| 950 |
-
|
| 951 |
-
[[package]]
|
| 952 |
-
name = "num-traits"
|
| 953 |
-
version = "0.2.19"
|
| 954 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 955 |
-
checksum = "071dfc062690e90b734c0b2273ce72ad0ffa95f0c74596bc250dcfd960262841"
|
| 956 |
-
dependencies = [
|
| 957 |
-
"autocfg",
|
| 958 |
-
]
|
| 959 |
-
|
| 960 |
-
[[package]]
|
| 961 |
-
name = "once_cell"
|
| 962 |
-
version = "1.21.4"
|
| 963 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 964 |
-
checksum = "9f7c3e4beb33f85d45ae3e3a1792185706c8e16d043238c593331cc7cd313b50"
|
| 965 |
-
|
| 966 |
-
[[package]]
|
| 967 |
-
name = "once_cell_polyfill"
|
| 968 |
-
version = "1.70.2"
|
| 969 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 970 |
-
checksum = "384b8ab6d37215f3c5301a95a4accb5d64aa607f1fcb26a11b5303878451b4fe"
|
| 971 |
-
|
| 972 |
-
[[package]]
|
| 973 |
-
name = "parking"
|
| 974 |
-
version = "2.2.1"
|
| 975 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 976 |
-
checksum = "f38d5652c16fde515bb1ecef450ab0f6a219d619a7274976324d5e377f7dceba"
|
| 977 |
-
|
| 978 |
-
[[package]]
|
| 979 |
-
name = "parking_lot"
|
| 980 |
-
version = "0.12.5"
|
| 981 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 982 |
-
checksum = "93857453250e3077bd71ff98b6a65ea6621a19bb0f559a85248955ac12c45a1a"
|
| 983 |
-
dependencies = [
|
| 984 |
-
"lock_api",
|
| 985 |
-
"parking_lot_core",
|
| 986 |
-
]
|
| 987 |
-
|
| 988 |
-
[[package]]
|
| 989 |
-
name = "parking_lot_core"
|
| 990 |
-
version = "0.9.12"
|
| 991 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 992 |
-
checksum = "2621685985a2ebf1c516881c026032ac7deafcda1a2c9b7850dc81e3dfcb64c1"
|
| 993 |
-
dependencies = [
|
| 994 |
-
"cfg-if",
|
| 995 |
-
"libc",
|
| 996 |
-
"redox_syscall 0.5.18",
|
| 997 |
-
"smallvec",
|
| 998 |
-
"windows-link",
|
| 999 |
-
]
|
| 1000 |
-
|
| 1001 |
-
[[package]]
|
| 1002 |
-
name = "percent-encoding"
|
| 1003 |
-
version = "2.3.2"
|
| 1004 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1005 |
-
checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220"
|
| 1006 |
-
|
| 1007 |
-
[[package]]
|
| 1008 |
-
name = "pin-project-lite"
|
| 1009 |
-
version = "0.2.17"
|
| 1010 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1011 |
-
checksum = "a89322df9ebe1c1578d689c92318e070967d1042b512afbe49518723f4e6d5cd"
|
| 1012 |
-
|
| 1013 |
-
[[package]]
|
| 1014 |
-
name = "plain"
|
| 1015 |
-
version = "0.2.3"
|
| 1016 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1017 |
-
checksum = "b4596b6d070b27117e987119b4dac604f3c58cfb0b191112e24771b2faeac1a6"
|
| 1018 |
-
|
| 1019 |
-
[[package]]
|
| 1020 |
-
name = "potential_utf"
|
| 1021 |
-
version = "0.1.5"
|
| 1022 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1023 |
-
checksum = "0103b1cef7ec0cf76490e969665504990193874ea05c85ff9bab8b911d0a0564"
|
| 1024 |
-
dependencies = [
|
| 1025 |
-
"zerovec",
|
| 1026 |
-
]
|
| 1027 |
-
|
| 1028 |
-
[[package]]
|
| 1029 |
-
name = "ppv-lite86"
|
| 1030 |
-
version = "0.2.21"
|
| 1031 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1032 |
-
checksum = "85eae3c4ed2f50dcfe72643da4befc30deadb458a9b590d720cde2f2b1e97da9"
|
| 1033 |
-
dependencies = [
|
| 1034 |
-
"zerocopy",
|
| 1035 |
-
]
|
| 1036 |
-
|
| 1037 |
-
[[package]]
|
| 1038 |
-
name = "proc-macro2"
|
| 1039 |
-
version = "1.0.106"
|
| 1040 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1041 |
-
checksum = "8fd00f0bb2e90d81d1044c2b32617f68fcb9fa3bb7640c23e9c748e53fb30934"
|
| 1042 |
-
dependencies = [
|
| 1043 |
-
"unicode-ident",
|
| 1044 |
-
]
|
| 1045 |
-
|
| 1046 |
-
[[package]]
|
| 1047 |
-
name = "quinn"
|
| 1048 |
-
version = "0.11.11"
|
| 1049 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1050 |
-
checksum = "0c1a41e437b6bbd489372cd4971de128e85c855f56c57f283d20ff016cf7c0a8"
|
| 1051 |
-
dependencies = [
|
| 1052 |
-
"bytes",
|
| 1053 |
-
"cfg_aliases",
|
| 1054 |
-
"pin-project-lite",
|
| 1055 |
-
"quinn-proto",
|
| 1056 |
-
"quinn-udp",
|
| 1057 |
-
"rustc-hash",
|
| 1058 |
-
"rustls",
|
| 1059 |
-
"socket2",
|
| 1060 |
-
"thiserror 2.0.18",
|
| 1061 |
-
"tokio",
|
| 1062 |
-
"tracing",
|
| 1063 |
-
"web-time",
|
| 1064 |
-
]
|
| 1065 |
-
|
| 1066 |
-
[[package]]
|
| 1067 |
-
name = "quinn-proto"
|
| 1068 |
-
version = "0.11.15"
|
| 1069 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1070 |
-
checksum = "4fcb935c5bec503c2f0e306bdd3e58bb9029dcb14fa8d9ac76e3a5256ac0763e"
|
| 1071 |
-
dependencies = [
|
| 1072 |
-
"bytes",
|
| 1073 |
-
"getrandom 0.3.4",
|
| 1074 |
-
"lru-slab",
|
| 1075 |
-
"rand 0.9.4",
|
| 1076 |
-
"ring",
|
| 1077 |
-
"rustc-hash",
|
| 1078 |
-
"rustls",
|
| 1079 |
-
"rustls-pki-types",
|
| 1080 |
-
"slab",
|
| 1081 |
-
"thiserror 2.0.18",
|
| 1082 |
-
"tinyvec",
|
| 1083 |
-
"tracing",
|
| 1084 |
-
"web-time",
|
| 1085 |
-
]
|
| 1086 |
-
|
| 1087 |
-
[[package]]
|
| 1088 |
-
name = "quinn-udp"
|
| 1089 |
-
version = "0.5.14"
|
| 1090 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1091 |
-
checksum = "addec6a0dcad8a8d96a771f815f0eaf55f9d1805756410b39f5fa81332574cbd"
|
| 1092 |
-
dependencies = [
|
| 1093 |
-
"cfg_aliases",
|
| 1094 |
-
"libc",
|
| 1095 |
-
"once_cell",
|
| 1096 |
-
"socket2",
|
| 1097 |
-
"tracing",
|
| 1098 |
-
"windows-sys 0.60.2",
|
| 1099 |
-
]
|
| 1100 |
-
|
| 1101 |
-
[[package]]
|
| 1102 |
-
name = "quote"
|
| 1103 |
-
version = "1.0.46"
|
| 1104 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1105 |
-
checksum = "dfbc457d0c7a0759a614551b11a6409e5951f6c7537be1f1b7682b9ae9230368"
|
| 1106 |
-
dependencies = [
|
| 1107 |
-
"proc-macro2",
|
| 1108 |
-
]
|
| 1109 |
-
|
| 1110 |
-
[[package]]
|
| 1111 |
-
name = "r-efi"
|
| 1112 |
-
version = "5.3.0"
|
| 1113 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1114 |
-
checksum = "69cdb34c158ceb288df11e18b4bd39de994f6657d83847bdffdbd7f346754b0f"
|
| 1115 |
-
|
| 1116 |
-
[[package]]
|
| 1117 |
-
name = "r-efi"
|
| 1118 |
-
version = "6.0.0"
|
| 1119 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1120 |
-
checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf"
|
| 1121 |
-
|
| 1122 |
-
[[package]]
|
| 1123 |
-
name = "rand"
|
| 1124 |
-
version = "0.8.6"
|
| 1125 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1126 |
-
checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a"
|
| 1127 |
-
dependencies = [
|
| 1128 |
-
"libc",
|
| 1129 |
-
"rand_chacha 0.3.1",
|
| 1130 |
-
"rand_core 0.6.4",
|
| 1131 |
-
]
|
| 1132 |
-
|
| 1133 |
-
[[package]]
|
| 1134 |
-
name = "rand"
|
| 1135 |
-
version = "0.9.4"
|
| 1136 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1137 |
-
checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea"
|
| 1138 |
-
dependencies = [
|
| 1139 |
-
"rand_chacha 0.9.0",
|
| 1140 |
-
"rand_core 0.9.5",
|
| 1141 |
-
]
|
| 1142 |
-
|
| 1143 |
-
[[package]]
|
| 1144 |
-
name = "rand_chacha"
|
| 1145 |
-
version = "0.3.1"
|
| 1146 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1147 |
-
checksum = "e6c10a63a0fa32252be49d21e7709d4d4baf8d231c2dbce1eaa8141b9b127d88"
|
| 1148 |
-
dependencies = [
|
| 1149 |
-
"ppv-lite86",
|
| 1150 |
-
"rand_core 0.6.4",
|
| 1151 |
-
]
|
| 1152 |
-
|
| 1153 |
-
[[package]]
|
| 1154 |
-
name = "rand_chacha"
|
| 1155 |
-
version = "0.9.0"
|
| 1156 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1157 |
-
checksum = "d3022b5f1df60f26e1ffddd6c66e8aa15de382ae63b3a0c1bfc0e4d3e3f325cb"
|
| 1158 |
-
dependencies = [
|
| 1159 |
-
"ppv-lite86",
|
| 1160 |
-
"rand_core 0.9.5",
|
| 1161 |
-
]
|
| 1162 |
-
|
| 1163 |
-
[[package]]
|
| 1164 |
-
name = "rand_core"
|
| 1165 |
-
version = "0.6.4"
|
| 1166 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1167 |
-
checksum = "ec0be4795e2f6a28069bec0b5ff3e2ac9bafc99e6a9a7dc3547996c5c816922c"
|
| 1168 |
-
dependencies = [
|
| 1169 |
-
"getrandom 0.2.17",
|
| 1170 |
-
]
|
| 1171 |
-
|
| 1172 |
-
[[package]]
|
| 1173 |
-
name = "rand_core"
|
| 1174 |
-
version = "0.9.5"
|
| 1175 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1176 |
-
checksum = "76afc826de14238e6e8c374ddcc1fa19e374fd8dd986b0d2af0d02377261d83c"
|
| 1177 |
-
dependencies = [
|
| 1178 |
-
"getrandom 0.3.4",
|
| 1179 |
-
]
|
| 1180 |
-
|
| 1181 |
-
[[package]]
|
| 1182 |
-
name = "redox_syscall"
|
| 1183 |
-
version = "0.5.18"
|
| 1184 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1185 |
-
checksum = "ed2bf2547551a7053d6fdfafda3f938979645c44812fbfcda098faae3f1a362d"
|
| 1186 |
-
dependencies = [
|
| 1187 |
-
"bitflags",
|
| 1188 |
-
]
|
| 1189 |
-
|
| 1190 |
-
[[package]]
|
| 1191 |
-
name = "redox_syscall"
|
| 1192 |
-
version = "0.9.0"
|
| 1193 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1194 |
-
checksum = "c5102a6aaa05aa011a238e178e6bca86d2cb56fc9f586d37cb80f5bca6e07759"
|
| 1195 |
-
dependencies = [
|
| 1196 |
-
"bitflags",
|
| 1197 |
-
]
|
| 1198 |
-
|
| 1199 |
-
[[package]]
|
| 1200 |
-
name = "regex"
|
| 1201 |
-
version = "1.12.4"
|
| 1202 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1203 |
-
checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba"
|
| 1204 |
-
dependencies = [
|
| 1205 |
-
"aho-corasick",
|
| 1206 |
-
"memchr",
|
| 1207 |
-
"regex-automata",
|
| 1208 |
-
"regex-syntax",
|
| 1209 |
-
]
|
| 1210 |
-
|
| 1211 |
-
[[package]]
|
| 1212 |
-
name = "regex-automata"
|
| 1213 |
-
version = "0.4.14"
|
| 1214 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1215 |
-
checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f"
|
| 1216 |
-
dependencies = [
|
| 1217 |
-
"aho-corasick",
|
| 1218 |
-
"memchr",
|
| 1219 |
-
"regex-syntax",
|
| 1220 |
-
]
|
| 1221 |
-
|
| 1222 |
-
[[package]]
|
| 1223 |
-
name = "regex-syntax"
|
| 1224 |
-
version = "0.8.11"
|
| 1225 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1226 |
-
checksum = "d6f6ff9a378485b298a5286656da665ba74413d36db0979633275d2e708145d4"
|
| 1227 |
-
|
| 1228 |
-
[[package]]
|
| 1229 |
-
name = "reqwest"
|
| 1230 |
-
version = "0.12.28"
|
| 1231 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1232 |
-
checksum = "eddd3ca559203180a307f12d114c268abf583f59b03cb906fd0b3ff8646c1147"
|
| 1233 |
-
dependencies = [
|
| 1234 |
-
"base64",
|
| 1235 |
-
"bytes",
|
| 1236 |
-
"futures-core",
|
| 1237 |
-
"http",
|
| 1238 |
-
"http-body",
|
| 1239 |
-
"http-body-util",
|
| 1240 |
-
"hyper",
|
| 1241 |
-
"hyper-rustls",
|
| 1242 |
-
"hyper-util",
|
| 1243 |
-
"js-sys",
|
| 1244 |
-
"log",
|
| 1245 |
-
"percent-encoding",
|
| 1246 |
-
"pin-project-lite",
|
| 1247 |
-
"quinn",
|
| 1248 |
-
"rustls",
|
| 1249 |
-
"rustls-pki-types",
|
| 1250 |
-
"serde",
|
| 1251 |
-
"serde_json",
|
| 1252 |
-
"serde_urlencoded",
|
| 1253 |
-
"sync_wrapper",
|
| 1254 |
-
"tokio",
|
| 1255 |
-
"tokio-rustls",
|
| 1256 |
-
"tower",
|
| 1257 |
-
"tower-http",
|
| 1258 |
-
"tower-service",
|
| 1259 |
-
"url",
|
| 1260 |
-
"wasm-bindgen",
|
| 1261 |
-
"wasm-bindgen-futures",
|
| 1262 |
-
"web-sys",
|
| 1263 |
-
"webpki-roots 1.0.8",
|
| 1264 |
-
]
|
| 1265 |
-
|
| 1266 |
-
[[package]]
|
| 1267 |
-
name = "ring"
|
| 1268 |
-
version = "0.17.14"
|
| 1269 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1270 |
-
checksum = "a4689e6c2294d81e88dc6261c768b63bc4fcdb852be6d1352498b114f61383b7"
|
| 1271 |
-
dependencies = [
|
| 1272 |
-
"cc",
|
| 1273 |
-
"cfg-if",
|
| 1274 |
-
"getrandom 0.2.17",
|
| 1275 |
-
"libc",
|
| 1276 |
-
"untrusted",
|
| 1277 |
-
"windows-sys 0.52.0",
|
| 1278 |
-
]
|
| 1279 |
-
|
| 1280 |
-
[[package]]
|
| 1281 |
-
name = "rustc-hash"
|
| 1282 |
-
version = "2.1.2"
|
| 1283 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1284 |
-
checksum = "94300abf3f1ae2e2b8ffb7b58043de3d399c73fa6f4b73826402a5c457614dbe"
|
| 1285 |
-
|
| 1286 |
-
[[package]]
|
| 1287 |
-
name = "rustix"
|
| 1288 |
-
version = "1.1.4"
|
| 1289 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1290 |
-
checksum = "b6fe4565b9518b83ef4f91bb47ce29620ca828bd32cb7e408f0062e9930ba190"
|
| 1291 |
-
dependencies = [
|
| 1292 |
-
"bitflags",
|
| 1293 |
-
"errno",
|
| 1294 |
-
"libc",
|
| 1295 |
-
"linux-raw-sys",
|
| 1296 |
-
"windows-sys 0.61.2",
|
| 1297 |
-
]
|
| 1298 |
-
|
| 1299 |
-
[[package]]
|
| 1300 |
-
name = "rustls"
|
| 1301 |
-
version = "0.23.41"
|
| 1302 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1303 |
-
checksum = "6b92b125634d9b795e7beca796cc790df15a7fb38323bf3196fda83292d06b1f"
|
| 1304 |
-
dependencies = [
|
| 1305 |
-
"once_cell",
|
| 1306 |
-
"ring",
|
| 1307 |
-
"rustls-pki-types",
|
| 1308 |
-
"rustls-webpki",
|
| 1309 |
-
"subtle",
|
| 1310 |
-
"zeroize",
|
| 1311 |
-
]
|
| 1312 |
-
|
| 1313 |
-
[[package]]
|
| 1314 |
-
name = "rustls-pki-types"
|
| 1315 |
-
version = "1.15.0"
|
| 1316 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1317 |
-
checksum = "764899a24af3980067ee14bc143654f297b22eaebfe3c7b6b211920a5a59b046"
|
| 1318 |
-
dependencies = [
|
| 1319 |
-
"web-time",
|
| 1320 |
-
"zeroize",
|
| 1321 |
-
]
|
| 1322 |
-
|
| 1323 |
-
[[package]]
|
| 1324 |
-
name = "rustls-webpki"
|
| 1325 |
-
version = "0.103.13"
|
| 1326 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1327 |
-
checksum = "61c429a8649f110dddef65e2a5ad240f747e85f7758a6bccc7e5777bd33f756e"
|
| 1328 |
-
dependencies = [
|
| 1329 |
-
"ring",
|
| 1330 |
-
"rustls-pki-types",
|
| 1331 |
-
"untrusted",
|
| 1332 |
-
]
|
| 1333 |
-
|
| 1334 |
-
[[package]]
|
| 1335 |
-
name = "rustversion"
|
| 1336 |
-
version = "1.0.22"
|
| 1337 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1338 |
-
checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d"
|
| 1339 |
-
|
| 1340 |
-
[[package]]
|
| 1341 |
-
name = "ryu"
|
| 1342 |
-
version = "1.0.23"
|
| 1343 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1344 |
-
checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f"
|
| 1345 |
-
|
| 1346 |
-
[[package]]
|
| 1347 |
-
name = "scopeguard"
|
| 1348 |
-
version = "1.2.0"
|
| 1349 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1350 |
-
checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
|
| 1351 |
-
|
| 1352 |
-
[[package]]
|
| 1353 |
-
name = "serde"
|
| 1354 |
-
version = "1.0.228"
|
| 1355 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1356 |
-
checksum = "9a8e94ea7f378bd32cbbd37198a4a91436180c5bb472411e48b5ec2e2124ae9e"
|
| 1357 |
-
dependencies = [
|
| 1358 |
-
"serde_core",
|
| 1359 |
-
"serde_derive",
|
| 1360 |
-
]
|
| 1361 |
-
|
| 1362 |
-
[[package]]
|
| 1363 |
-
name = "serde_core"
|
| 1364 |
-
version = "1.0.228"
|
| 1365 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1366 |
-
checksum = "41d385c7d4ca58e59fc732af25c3983b67ac852c1a25000afe1175de458b67ad"
|
| 1367 |
-
dependencies = [
|
| 1368 |
-
"serde_derive",
|
| 1369 |
-
]
|
| 1370 |
-
|
| 1371 |
-
[[package]]
|
| 1372 |
-
name = "serde_derive"
|
| 1373 |
-
version = "1.0.228"
|
| 1374 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1375 |
-
checksum = "d540f220d3187173da220f885ab66608367b6574e925011a9353e4badda91d79"
|
| 1376 |
-
dependencies = [
|
| 1377 |
-
"proc-macro2",
|
| 1378 |
-
"quote",
|
| 1379 |
-
"syn",
|
| 1380 |
-
]
|
| 1381 |
-
|
| 1382 |
-
[[package]]
|
| 1383 |
-
name = "serde_json"
|
| 1384 |
-
version = "1.0.150"
|
| 1385 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1386 |
-
checksum = "e8014e44b4736ed0538adeecded0fce2a272f22dc9578a7eb6b2d9993c74cfb9"
|
| 1387 |
-
dependencies = [
|
| 1388 |
-
"itoa",
|
| 1389 |
-
"memchr",
|
| 1390 |
-
"serde",
|
| 1391 |
-
"serde_core",
|
| 1392 |
-
"zmij",
|
| 1393 |
-
]
|
| 1394 |
-
|
| 1395 |
-
[[package]]
|
| 1396 |
-
name = "serde_path_to_error"
|
| 1397 |
-
version = "0.1.20"
|
| 1398 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1399 |
-
checksum = "10a9ff822e371bb5403e391ecd83e182e0e77ba7f6fe0160b795797109d1b457"
|
| 1400 |
-
dependencies = [
|
| 1401 |
-
"itoa",
|
| 1402 |
-
"serde",
|
| 1403 |
-
"serde_core",
|
| 1404 |
-
]
|
| 1405 |
-
|
| 1406 |
-
[[package]]
|
| 1407 |
-
name = "serde_urlencoded"
|
| 1408 |
-
version = "0.7.1"
|
| 1409 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1410 |
-
checksum = "d3491c14715ca2294c4d6a88f15e84739788c1d030eed8c110436aafdaa2f3fd"
|
| 1411 |
-
dependencies = [
|
| 1412 |
-
"form_urlencoded",
|
| 1413 |
-
"itoa",
|
| 1414 |
-
"ryu",
|
| 1415 |
-
"serde",
|
| 1416 |
-
]
|
| 1417 |
-
|
| 1418 |
-
[[package]]
|
| 1419 |
-
name = "sha2"
|
| 1420 |
-
version = "0.10.9"
|
| 1421 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1422 |
-
checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283"
|
| 1423 |
-
dependencies = [
|
| 1424 |
-
"cfg-if",
|
| 1425 |
-
"cpufeatures",
|
| 1426 |
-
"digest",
|
| 1427 |
-
]
|
| 1428 |
-
|
| 1429 |
-
[[package]]
|
| 1430 |
-
name = "shlex"
|
| 1431 |
-
version = "2.0.1"
|
| 1432 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1433 |
-
checksum = "f8fadd59c855ef2080decdef8ff161eb6661b86933c9d82e5ba29dc602a55aba"
|
| 1434 |
-
|
| 1435 |
-
[[package]]
|
| 1436 |
-
name = "slab"
|
| 1437 |
-
version = "0.4.12"
|
| 1438 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1439 |
-
checksum = "0c790de23124f9ab44544d7ac05d60440adc586479ce501c1d6d7da3cd8c9cf5"
|
| 1440 |
-
|
| 1441 |
-
[[package]]
|
| 1442 |
-
name = "smallvec"
|
| 1443 |
-
version = "1.15.2"
|
| 1444 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1445 |
-
checksum = "8ed6a63f02c8539c91a8685a86f4099661ba3da017932f6ebbea6de3f0fa7c90"
|
| 1446 |
-
dependencies = [
|
| 1447 |
-
"serde",
|
| 1448 |
-
]
|
| 1449 |
-
|
| 1450 |
-
[[package]]
|
| 1451 |
-
name = "socket2"
|
| 1452 |
-
version = "0.6.4"
|
| 1453 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1454 |
-
checksum = "52d1cfed4120b4d927bf7c0f86d2087a4a7d6027c906d9f9d525a80573b9be51"
|
| 1455 |
-
dependencies = [
|
| 1456 |
-
"libc",
|
| 1457 |
-
"windows-sys 0.61.2",
|
| 1458 |
-
]
|
| 1459 |
-
|
| 1460 |
-
[[package]]
|
| 1461 |
-
name = "sqlx"
|
| 1462 |
-
version = "0.8.6"
|
| 1463 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1464 |
-
checksum = "1fefb893899429669dcdd979aff487bd78f4064e5e7907e4269081e0ef7d97dc"
|
| 1465 |
-
dependencies = [
|
| 1466 |
-
"sqlx-core",
|
| 1467 |
-
"sqlx-macros",
|
| 1468 |
-
"sqlx-postgres",
|
| 1469 |
-
]
|
| 1470 |
-
|
| 1471 |
-
[[package]]
|
| 1472 |
-
name = "sqlx-core"
|
| 1473 |
-
version = "0.8.6"
|
| 1474 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1475 |
-
checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6"
|
| 1476 |
-
dependencies = [
|
| 1477 |
-
"base64",
|
| 1478 |
-
"bytes",
|
| 1479 |
-
"crc",
|
| 1480 |
-
"crossbeam-queue",
|
| 1481 |
-
"either",
|
| 1482 |
-
"event-listener",
|
| 1483 |
-
"futures-core",
|
| 1484 |
-
"futures-intrusive",
|
| 1485 |
-
"futures-io",
|
| 1486 |
-
"futures-util",
|
| 1487 |
-
"hashbrown 0.15.5",
|
| 1488 |
-
"hashlink",
|
| 1489 |
-
"indexmap",
|
| 1490 |
-
"log",
|
| 1491 |
-
"memchr",
|
| 1492 |
-
"once_cell",
|
| 1493 |
-
"percent-encoding",
|
| 1494 |
-
"rustls",
|
| 1495 |
-
"serde",
|
| 1496 |
-
"serde_json",
|
| 1497 |
-
"sha2",
|
| 1498 |
-
"smallvec",
|
| 1499 |
-
"thiserror 2.0.18",
|
| 1500 |
-
"tokio",
|
| 1501 |
-
"tokio-stream",
|
| 1502 |
-
"tracing",
|
| 1503 |
-
"url",
|
| 1504 |
-
"webpki-roots 0.26.11",
|
| 1505 |
-
]
|
| 1506 |
-
|
| 1507 |
-
[[package]]
|
| 1508 |
-
name = "sqlx-macros"
|
| 1509 |
-
version = "0.8.6"
|
| 1510 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1511 |
-
checksum = "a2d452988ccaacfbf5e0bdbc348fb91d7c8af5bee192173ac3636b5fb6e6715d"
|
| 1512 |
-
dependencies = [
|
| 1513 |
-
"proc-macro2",
|
| 1514 |
-
"quote",
|
| 1515 |
-
"sqlx-core",
|
| 1516 |
-
"sqlx-macros-core",
|
| 1517 |
-
"syn",
|
| 1518 |
-
]
|
| 1519 |
-
|
| 1520 |
-
[[package]]
|
| 1521 |
-
name = "sqlx-macros-core"
|
| 1522 |
-
version = "0.8.6"
|
| 1523 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1524 |
-
checksum = "19a9c1841124ac5a61741f96e1d9e2ec77424bf323962dd894bdb93f37d5219b"
|
| 1525 |
-
dependencies = [
|
| 1526 |
-
"dotenvy",
|
| 1527 |
-
"either",
|
| 1528 |
-
"heck",
|
| 1529 |
-
"hex",
|
| 1530 |
-
"once_cell",
|
| 1531 |
-
"proc-macro2",
|
| 1532 |
-
"quote",
|
| 1533 |
-
"serde",
|
| 1534 |
-
"serde_json",
|
| 1535 |
-
"sha2",
|
| 1536 |
-
"sqlx-core",
|
| 1537 |
-
"sqlx-postgres",
|
| 1538 |
-
"syn",
|
| 1539 |
-
"tokio",
|
| 1540 |
-
"url",
|
| 1541 |
-
]
|
| 1542 |
-
|
| 1543 |
-
[[package]]
|
| 1544 |
-
name = "sqlx-postgres"
|
| 1545 |
-
version = "0.8.6"
|
| 1546 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1547 |
-
checksum = "db58fcd5a53cf07c184b154801ff91347e4c30d17a3562a635ff028ad5deda46"
|
| 1548 |
-
dependencies = [
|
| 1549 |
-
"atoi",
|
| 1550 |
-
"base64",
|
| 1551 |
-
"bitflags",
|
| 1552 |
-
"byteorder",
|
| 1553 |
-
"crc",
|
| 1554 |
-
"dotenvy",
|
| 1555 |
-
"etcetera",
|
| 1556 |
-
"futures-channel",
|
| 1557 |
-
"futures-core",
|
| 1558 |
-
"futures-util",
|
| 1559 |
-
"hex",
|
| 1560 |
-
"hkdf",
|
| 1561 |
-
"hmac",
|
| 1562 |
-
"home",
|
| 1563 |
-
"itoa",
|
| 1564 |
-
"log",
|
| 1565 |
-
"md-5",
|
| 1566 |
-
"memchr",
|
| 1567 |
-
"once_cell",
|
| 1568 |
-
"rand 0.8.6",
|
| 1569 |
-
"serde",
|
| 1570 |
-
"serde_json",
|
| 1571 |
-
"sha2",
|
| 1572 |
-
"smallvec",
|
| 1573 |
-
"sqlx-core",
|
| 1574 |
-
"stringprep",
|
| 1575 |
-
"thiserror 2.0.18",
|
| 1576 |
-
"tracing",
|
| 1577 |
-
"whoami",
|
| 1578 |
-
]
|
| 1579 |
-
|
| 1580 |
-
[[package]]
|
| 1581 |
-
name = "stable_deref_trait"
|
| 1582 |
-
version = "1.2.1"
|
| 1583 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1584 |
-
checksum = "6ce2be8dc25455e1f91df71bfa12ad37d7af1092ae736f3a6cd0e37bc7810596"
|
| 1585 |
-
|
| 1586 |
-
[[package]]
|
| 1587 |
-
name = "stringprep"
|
| 1588 |
-
version = "0.1.5"
|
| 1589 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1590 |
-
checksum = "7b4df3d392d81bd458a8a621b8bffbd2302a12ffe288a9d931670948749463b1"
|
| 1591 |
-
dependencies = [
|
| 1592 |
-
"unicode-bidi",
|
| 1593 |
-
"unicode-normalization",
|
| 1594 |
-
"unicode-properties",
|
| 1595 |
-
]
|
| 1596 |
-
|
| 1597 |
-
[[package]]
|
| 1598 |
-
name = "strsim"
|
| 1599 |
-
version = "0.11.1"
|
| 1600 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1601 |
-
checksum = "7da8b5736845d9f2fcb837ea5d9e2628564b3b043a70948a3f0b778838c5fb4f"
|
| 1602 |
-
|
| 1603 |
-
[[package]]
|
| 1604 |
-
name = "subtle"
|
| 1605 |
-
version = "2.6.1"
|
| 1606 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1607 |
-
checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292"
|
| 1608 |
-
|
| 1609 |
-
[[package]]
|
| 1610 |
-
name = "syn"
|
| 1611 |
-
version = "2.0.118"
|
| 1612 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1613 |
-
checksum = "1b9ae57f904213ebb649ce6895b8a66c66f0203b9319718f69a5612a065b1422"
|
| 1614 |
-
dependencies = [
|
| 1615 |
-
"proc-macro2",
|
| 1616 |
-
"quote",
|
| 1617 |
-
"unicode-ident",
|
| 1618 |
-
]
|
| 1619 |
-
|
| 1620 |
-
[[package]]
|
| 1621 |
-
name = "sync_wrapper"
|
| 1622 |
-
version = "1.0.2"
|
| 1623 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1624 |
-
checksum = "0bf256ce5efdfa370213c1dabab5935a12e49f2c58d15e9eac2870d3b4f27263"
|
| 1625 |
-
dependencies = [
|
| 1626 |
-
"futures-core",
|
| 1627 |
-
]
|
| 1628 |
-
|
| 1629 |
-
[[package]]
|
| 1630 |
-
name = "synstructure"
|
| 1631 |
-
version = "0.13.2"
|
| 1632 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1633 |
-
checksum = "728a70f3dbaf5bab7f0c4b1ac8d7ae5ea60a4b5549c8a5914361c99147a709d2"
|
| 1634 |
-
dependencies = [
|
| 1635 |
-
"proc-macro2",
|
| 1636 |
-
"quote",
|
| 1637 |
-
"syn",
|
| 1638 |
-
]
|
| 1639 |
-
|
| 1640 |
-
[[package]]
|
| 1641 |
-
name = "tempfile"
|
| 1642 |
-
version = "3.27.0"
|
| 1643 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1644 |
-
checksum = "32497e9a4c7b38532efcdebeef879707aa9f794296a4f0244f6f69e9bc8574bd"
|
| 1645 |
-
dependencies = [
|
| 1646 |
-
"fastrand",
|
| 1647 |
-
"getrandom 0.4.3",
|
| 1648 |
-
"once_cell",
|
| 1649 |
-
"rustix",
|
| 1650 |
-
"windows-sys 0.61.2",
|
| 1651 |
-
]
|
| 1652 |
-
|
| 1653 |
-
[[package]]
|
| 1654 |
-
name = "thiserror"
|
| 1655 |
-
version = "1.0.69"
|
| 1656 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1657 |
-
checksum = "b6aaf5339b578ea85b50e080feb250a3e8ae8cfcdff9a461c9ec2904bc923f52"
|
| 1658 |
-
dependencies = [
|
| 1659 |
-
"thiserror-impl 1.0.69",
|
| 1660 |
-
]
|
| 1661 |
-
|
| 1662 |
-
[[package]]
|
| 1663 |
-
name = "thiserror"
|
| 1664 |
-
version = "2.0.18"
|
| 1665 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1666 |
-
checksum = "4288b5bcbc7920c07a1149a35cf9590a2aa808e0bc1eafaade0b80947865fbc4"
|
| 1667 |
-
dependencies = [
|
| 1668 |
-
"thiserror-impl 2.0.18",
|
| 1669 |
-
]
|
| 1670 |
-
|
| 1671 |
-
[[package]]
|
| 1672 |
-
name = "thiserror-impl"
|
| 1673 |
-
version = "1.0.69"
|
| 1674 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1675 |
-
checksum = "4fee6c4efc90059e10f81e6d42c60a18f76588c3d74cb83a0b242a2b6c7504c1"
|
| 1676 |
-
dependencies = [
|
| 1677 |
-
"proc-macro2",
|
| 1678 |
-
"quote",
|
| 1679 |
-
"syn",
|
| 1680 |
-
]
|
| 1681 |
-
|
| 1682 |
-
[[package]]
|
| 1683 |
-
name = "thiserror-impl"
|
| 1684 |
-
version = "2.0.18"
|
| 1685 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1686 |
-
checksum = "ebc4ee7f67670e9b64d05fa4253e753e016c6c95ff35b89b7941d6b856dec1d5"
|
| 1687 |
-
dependencies = [
|
| 1688 |
-
"proc-macro2",
|
| 1689 |
-
"quote",
|
| 1690 |
-
"syn",
|
| 1691 |
-
]
|
| 1692 |
-
|
| 1693 |
-
[[package]]
|
| 1694 |
-
name = "tinystr"
|
| 1695 |
-
version = "0.8.3"
|
| 1696 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1697 |
-
checksum = "c8323304221c2a851516f22236c5722a72eaa19749016521d6dff0824447d96d"
|
| 1698 |
-
dependencies = [
|
| 1699 |
-
"displaydoc",
|
| 1700 |
-
"zerovec",
|
| 1701 |
-
]
|
| 1702 |
-
|
| 1703 |
-
[[package]]
|
| 1704 |
-
name = "tinyvec"
|
| 1705 |
-
version = "1.11.0"
|
| 1706 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1707 |
-
checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3"
|
| 1708 |
-
dependencies = [
|
| 1709 |
-
"tinyvec_macros",
|
| 1710 |
-
]
|
| 1711 |
-
|
| 1712 |
-
[[package]]
|
| 1713 |
-
name = "tinyvec_macros"
|
| 1714 |
-
version = "0.1.1"
|
| 1715 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1716 |
-
checksum = "1f3ccbac311fea05f86f61904b462b55fb3df8837a366dfc601a0161d0532f20"
|
| 1717 |
-
|
| 1718 |
-
[[package]]
|
| 1719 |
-
name = "tokio"
|
| 1720 |
-
version = "1.52.3"
|
| 1721 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1722 |
-
checksum = "8fc7f01b389ac15039e4dc9531aa973a135d7a4135281b12d7c1bc79fd57fffe"
|
| 1723 |
-
dependencies = [
|
| 1724 |
-
"bytes",
|
| 1725 |
-
"libc",
|
| 1726 |
-
"mio",
|
| 1727 |
-
"pin-project-lite",
|
| 1728 |
-
"socket2",
|
| 1729 |
-
"tokio-macros",
|
| 1730 |
-
"windows-sys 0.61.2",
|
| 1731 |
-
]
|
| 1732 |
-
|
| 1733 |
-
[[package]]
|
| 1734 |
-
name = "tokio-macros"
|
| 1735 |
-
version = "2.7.0"
|
| 1736 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1737 |
-
checksum = "385a6cb71ab9ab790c5fe8d67f1645e6c450a7ce006a33de03daa956cf70a496"
|
| 1738 |
-
dependencies = [
|
| 1739 |
-
"proc-macro2",
|
| 1740 |
-
"quote",
|
| 1741 |
-
"syn",
|
| 1742 |
-
]
|
| 1743 |
-
|
| 1744 |
-
[[package]]
|
| 1745 |
-
name = "tokio-rustls"
|
| 1746 |
-
version = "0.26.4"
|
| 1747 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1748 |
-
checksum = "1729aa945f29d91ba541258c8df89027d5792d85a8841fb65e8bf0f4ede4ef61"
|
| 1749 |
-
dependencies = [
|
| 1750 |
-
"rustls",
|
| 1751 |
-
"tokio",
|
| 1752 |
-
]
|
| 1753 |
-
|
| 1754 |
-
[[package]]
|
| 1755 |
-
name = "tokio-stream"
|
| 1756 |
-
version = "0.1.18"
|
| 1757 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1758 |
-
checksum = "32da49809aab5c3bc678af03902d4ccddea2a87d028d86392a4b1560c6906c70"
|
| 1759 |
-
dependencies = [
|
| 1760 |
-
"futures-core",
|
| 1761 |
-
"pin-project-lite",
|
| 1762 |
-
"tokio",
|
| 1763 |
-
]
|
| 1764 |
-
|
| 1765 |
-
[[package]]
|
| 1766 |
-
name = "tower"
|
| 1767 |
-
version = "0.5.3"
|
| 1768 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1769 |
-
checksum = "ebe5ef63511595f1344e2d5cfa636d973292adc0eec1f0ad45fae9f0851ab1d4"
|
| 1770 |
-
dependencies = [
|
| 1771 |
-
"futures-core",
|
| 1772 |
-
"futures-util",
|
| 1773 |
-
"pin-project-lite",
|
| 1774 |
-
"sync_wrapper",
|
| 1775 |
-
"tokio",
|
| 1776 |
-
"tower-layer",
|
| 1777 |
-
"tower-service",
|
| 1778 |
-
"tracing",
|
| 1779 |
-
]
|
| 1780 |
-
|
| 1781 |
-
[[package]]
|
| 1782 |
-
name = "tower-http"
|
| 1783 |
-
version = "0.6.11"
|
| 1784 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1785 |
-
checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840"
|
| 1786 |
-
dependencies = [
|
| 1787 |
-
"bitflags",
|
| 1788 |
-
"bytes",
|
| 1789 |
-
"futures-util",
|
| 1790 |
-
"http",
|
| 1791 |
-
"http-body",
|
| 1792 |
-
"pin-project-lite",
|
| 1793 |
-
"tower",
|
| 1794 |
-
"tower-layer",
|
| 1795 |
-
"tower-service",
|
| 1796 |
-
"url",
|
| 1797 |
-
]
|
| 1798 |
-
|
| 1799 |
-
[[package]]
|
| 1800 |
-
name = "tower-layer"
|
| 1801 |
-
version = "0.3.3"
|
| 1802 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1803 |
-
checksum = "121c2a6cda46980bb0fcd1647ffaf6cd3fc79a013de288782836f6df9c48780e"
|
| 1804 |
-
|
| 1805 |
-
[[package]]
|
| 1806 |
-
name = "tower-service"
|
| 1807 |
-
version = "0.3.3"
|
| 1808 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1809 |
-
checksum = "8df9b6e13f2d32c91b9bd719c00d1958837bc7dec474d94952798cc8e69eeec3"
|
| 1810 |
-
|
| 1811 |
-
[[package]]
|
| 1812 |
-
name = "tracing"
|
| 1813 |
-
version = "0.1.44"
|
| 1814 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1815 |
-
checksum = "63e71662fa4b2a2c3a26f570f037eb95bb1f85397f3cd8076caed2f026a6d100"
|
| 1816 |
-
dependencies = [
|
| 1817 |
-
"log",
|
| 1818 |
-
"pin-project-lite",
|
| 1819 |
-
"tracing-attributes",
|
| 1820 |
-
"tracing-core",
|
| 1821 |
-
]
|
| 1822 |
-
|
| 1823 |
-
[[package]]
|
| 1824 |
-
name = "tracing-attributes"
|
| 1825 |
-
version = "0.1.31"
|
| 1826 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1827 |
-
checksum = "7490cfa5ec963746568740651ac6781f701c9c5ea257c58e057f3ba8cf69e8da"
|
| 1828 |
-
dependencies = [
|
| 1829 |
-
"proc-macro2",
|
| 1830 |
-
"quote",
|
| 1831 |
-
"syn",
|
| 1832 |
-
]
|
| 1833 |
-
|
| 1834 |
-
[[package]]
|
| 1835 |
-
name = "tracing-core"
|
| 1836 |
-
version = "0.1.36"
|
| 1837 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1838 |
-
checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a"
|
| 1839 |
-
dependencies = [
|
| 1840 |
-
"once_cell",
|
| 1841 |
-
]
|
| 1842 |
-
|
| 1843 |
-
[[package]]
|
| 1844 |
-
name = "try-lock"
|
| 1845 |
-
version = "0.2.5"
|
| 1846 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1847 |
-
checksum = "e421abadd41a4225275504ea4d6566923418b7f05506fbc9c0fe86ba7396114b"
|
| 1848 |
-
|
| 1849 |
-
[[package]]
|
| 1850 |
-
name = "typenum"
|
| 1851 |
-
version = "1.20.1"
|
| 1852 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1853 |
-
checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20"
|
| 1854 |
-
|
| 1855 |
-
[[package]]
|
| 1856 |
-
name = "unicode-bidi"
|
| 1857 |
-
version = "0.3.18"
|
| 1858 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1859 |
-
checksum = "5c1cb5db39152898a79168971543b1cb5020dff7fe43c8dc468b0885f5e29df5"
|
| 1860 |
-
|
| 1861 |
-
[[package]]
|
| 1862 |
-
name = "unicode-ident"
|
| 1863 |
-
version = "1.0.24"
|
| 1864 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1865 |
-
checksum = "e6e4313cd5fcd3dad5cafa179702e2b244f760991f45397d14d4ebf38247da75"
|
| 1866 |
-
|
| 1867 |
-
[[package]]
|
| 1868 |
-
name = "unicode-normalization"
|
| 1869 |
-
version = "0.1.25"
|
| 1870 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1871 |
-
checksum = "5fd4f6878c9cb28d874b009da9e8d183b5abc80117c40bbd187a1fde336be6e8"
|
| 1872 |
-
dependencies = [
|
| 1873 |
-
"tinyvec",
|
| 1874 |
-
]
|
| 1875 |
-
|
| 1876 |
-
[[package]]
|
| 1877 |
-
name = "unicode-properties"
|
| 1878 |
-
version = "0.1.4"
|
| 1879 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1880 |
-
checksum = "7df058c713841ad818f1dc5d3fd88063241cc61f49f5fbea4b951e8cf5a8d71d"
|
| 1881 |
-
|
| 1882 |
-
[[package]]
|
| 1883 |
-
name = "untrusted"
|
| 1884 |
-
version = "0.9.0"
|
| 1885 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1886 |
-
checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1"
|
| 1887 |
-
|
| 1888 |
-
[[package]]
|
| 1889 |
-
name = "url"
|
| 1890 |
-
version = "2.5.8"
|
| 1891 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1892 |
-
checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed"
|
| 1893 |
-
dependencies = [
|
| 1894 |
-
"form_urlencoded",
|
| 1895 |
-
"idna",
|
| 1896 |
-
"percent-encoding",
|
| 1897 |
-
"serde",
|
| 1898 |
-
]
|
| 1899 |
-
|
| 1900 |
-
[[package]]
|
| 1901 |
-
name = "utf8_iter"
|
| 1902 |
-
version = "1.0.4"
|
| 1903 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1904 |
-
checksum = "b6c140620e7ffbb22c2dee59cafe6084a59b5ffc27a8859a5f0d494b5d52b6be"
|
| 1905 |
-
|
| 1906 |
-
[[package]]
|
| 1907 |
-
name = "utf8parse"
|
| 1908 |
-
version = "0.2.2"
|
| 1909 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1910 |
-
checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821"
|
| 1911 |
-
|
| 1912 |
-
[[package]]
|
| 1913 |
-
name = "uuid"
|
| 1914 |
-
version = "1.23.4"
|
| 1915 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1916 |
-
checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53"
|
| 1917 |
-
dependencies = [
|
| 1918 |
-
"getrandom 0.4.3",
|
| 1919 |
-
"js-sys",
|
| 1920 |
-
"serde_core",
|
| 1921 |
-
"wasm-bindgen",
|
| 1922 |
-
]
|
| 1923 |
-
|
| 1924 |
-
[[package]]
|
| 1925 |
-
name = "version_check"
|
| 1926 |
-
version = "0.9.5"
|
| 1927 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1928 |
-
checksum = "0b928f33d975fc6ad9f86c8f283853ad26bdd5b10b7f1542aa2fa15e2289105a"
|
| 1929 |
-
|
| 1930 |
-
[[package]]
|
| 1931 |
-
name = "want"
|
| 1932 |
-
version = "0.3.1"
|
| 1933 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1934 |
-
checksum = "bfa7760aed19e106de2c7c0b581b509f2f25d3dacaf737cb82ac61bc6d760b0e"
|
| 1935 |
-
dependencies = [
|
| 1936 |
-
"try-lock",
|
| 1937 |
-
]
|
| 1938 |
-
|
| 1939 |
-
[[package]]
|
| 1940 |
-
name = "wasi"
|
| 1941 |
-
version = "0.11.1+wasi-snapshot-preview1"
|
| 1942 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1943 |
-
checksum = "ccf3ec651a847eb01de73ccad15eb7d99f80485de043efb2f370cd654f4ea44b"
|
| 1944 |
-
|
| 1945 |
-
[[package]]
|
| 1946 |
-
name = "wasip2"
|
| 1947 |
-
version = "1.0.4+wasi-0.2.12"
|
| 1948 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1949 |
-
checksum = "b67efb37e106e55ce722a510d6b5f9c17f083e5fc79afc2badeb12cc313d9487"
|
| 1950 |
-
dependencies = [
|
| 1951 |
-
"wit-bindgen",
|
| 1952 |
-
]
|
| 1953 |
-
|
| 1954 |
-
[[package]]
|
| 1955 |
-
name = "wasite"
|
| 1956 |
-
version = "0.1.0"
|
| 1957 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1958 |
-
checksum = "b8dad83b4f25e74f184f64c43b150b91efe7647395b42289f38e50566d82855b"
|
| 1959 |
-
|
| 1960 |
-
[[package]]
|
| 1961 |
-
name = "wasm-bindgen"
|
| 1962 |
-
version = "0.2.126"
|
| 1963 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1964 |
-
checksum = "4b067c0c11094aef6b7a801c1e34a26affafdf3d051dba08456b868789aaf9a4"
|
| 1965 |
-
dependencies = [
|
| 1966 |
-
"cfg-if",
|
| 1967 |
-
"once_cell",
|
| 1968 |
-
"rustversion",
|
| 1969 |
-
"wasm-bindgen-macro",
|
| 1970 |
-
"wasm-bindgen-shared",
|
| 1971 |
-
]
|
| 1972 |
-
|
| 1973 |
-
[[package]]
|
| 1974 |
-
name = "wasm-bindgen-futures"
|
| 1975 |
-
version = "0.4.76"
|
| 1976 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1977 |
-
checksum = "c62df1340f32221cb9c54d6a27b030e3dba64361d4a95bed55f9aacb44da291d"
|
| 1978 |
-
dependencies = [
|
| 1979 |
-
"js-sys",
|
| 1980 |
-
"wasm-bindgen",
|
| 1981 |
-
]
|
| 1982 |
-
|
| 1983 |
-
[[package]]
|
| 1984 |
-
name = "wasm-bindgen-macro"
|
| 1985 |
-
version = "0.2.126"
|
| 1986 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1987 |
-
checksum = "167ce5e579f6bcf889c4f7175a8a5a585de84e8ff93976ce393efa5f2837aab1"
|
| 1988 |
-
dependencies = [
|
| 1989 |
-
"quote",
|
| 1990 |
-
"wasm-bindgen-macro-support",
|
| 1991 |
-
]
|
| 1992 |
-
|
| 1993 |
-
[[package]]
|
| 1994 |
-
name = "wasm-bindgen-macro-support"
|
| 1995 |
-
version = "0.2.126"
|
| 1996 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 1997 |
-
checksum = "f3997c7839262f4ef12cf90b818d6340c18e80f263f1a94bf157d0ec4420380e"
|
| 1998 |
-
dependencies = [
|
| 1999 |
-
"bumpalo",
|
| 2000 |
-
"proc-macro2",
|
| 2001 |
-
"quote",
|
| 2002 |
-
"syn",
|
| 2003 |
-
"wasm-bindgen-shared",
|
| 2004 |
-
]
|
| 2005 |
-
|
| 2006 |
-
[[package]]
|
| 2007 |
-
name = "wasm-bindgen-shared"
|
| 2008 |
-
version = "0.2.126"
|
| 2009 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2010 |
-
checksum = "dc1b4cb0cc549fcf58d7dfc081778139b3d283a081644e833e84682ad71cea24"
|
| 2011 |
-
dependencies = [
|
| 2012 |
-
"unicode-ident",
|
| 2013 |
-
]
|
| 2014 |
-
|
| 2015 |
-
[[package]]
|
| 2016 |
-
name = "web-sys"
|
| 2017 |
-
version = "0.3.103"
|
| 2018 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2019 |
-
checksum = "8622dcb61c0bcc9fffa6938bed81210af2da9a7e4a1a834b2e37a59b6dfb6141"
|
| 2020 |
-
dependencies = [
|
| 2021 |
-
"js-sys",
|
| 2022 |
-
"wasm-bindgen",
|
| 2023 |
-
]
|
| 2024 |
-
|
| 2025 |
-
[[package]]
|
| 2026 |
-
name = "web-time"
|
| 2027 |
-
version = "1.1.0"
|
| 2028 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2029 |
-
checksum = "5a6580f308b1fad9207618087a65c04e7a10bc77e02c8e84e9b00dd4b12fa0bb"
|
| 2030 |
-
dependencies = [
|
| 2031 |
-
"js-sys",
|
| 2032 |
-
"wasm-bindgen",
|
| 2033 |
-
]
|
| 2034 |
-
|
| 2035 |
-
[[package]]
|
| 2036 |
-
name = "webpki-roots"
|
| 2037 |
-
version = "0.26.11"
|
| 2038 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2039 |
-
checksum = "521bc38abb08001b01866da9f51eb7c5d647a19260e00054a8c7fd5f9e57f7a9"
|
| 2040 |
-
dependencies = [
|
| 2041 |
-
"webpki-roots 1.0.8",
|
| 2042 |
-
]
|
| 2043 |
-
|
| 2044 |
-
[[package]]
|
| 2045 |
-
name = "webpki-roots"
|
| 2046 |
-
version = "1.0.8"
|
| 2047 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2048 |
-
checksum = "bf85cb06032201fa7c6f829d7db5a7e5aa45bcc0655327713065f6f0576731bf"
|
| 2049 |
-
dependencies = [
|
| 2050 |
-
"rustls-pki-types",
|
| 2051 |
-
]
|
| 2052 |
-
|
| 2053 |
-
[[package]]
|
| 2054 |
-
name = "whoami"
|
| 2055 |
-
version = "1.6.1"
|
| 2056 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2057 |
-
checksum = "5d4a4db5077702ca3015d3d02d74974948aba2ad9e12ab7df718ee64ccd7e97d"
|
| 2058 |
-
dependencies = [
|
| 2059 |
-
"libredox",
|
| 2060 |
-
"wasite",
|
| 2061 |
-
]
|
| 2062 |
-
|
| 2063 |
-
[[package]]
|
| 2064 |
-
name = "windows-link"
|
| 2065 |
-
version = "0.2.1"
|
| 2066 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2067 |
-
checksum = "f0805222e57f7521d6a62e36fa9163bc891acd422f971defe97d64e70d0a4fe5"
|
| 2068 |
-
|
| 2069 |
-
[[package]]
|
| 2070 |
-
name = "windows-sys"
|
| 2071 |
-
version = "0.48.0"
|
| 2072 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2073 |
-
checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9"
|
| 2074 |
-
dependencies = [
|
| 2075 |
-
"windows-targets 0.48.5",
|
| 2076 |
-
]
|
| 2077 |
-
|
| 2078 |
-
[[package]]
|
| 2079 |
-
name = "windows-sys"
|
| 2080 |
-
version = "0.52.0"
|
| 2081 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2082 |
-
checksum = "282be5f36a8ce781fad8c8ae18fa3f9beff57ec1b52cb3de0789201425d9a33d"
|
| 2083 |
-
dependencies = [
|
| 2084 |
-
"windows-targets 0.52.6",
|
| 2085 |
-
]
|
| 2086 |
-
|
| 2087 |
-
[[package]]
|
| 2088 |
-
name = "windows-sys"
|
| 2089 |
-
version = "0.60.2"
|
| 2090 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2091 |
-
checksum = "f2f500e4d28234f72040990ec9d39e3a6b950f9f22d3dba18416c35882612bcb"
|
| 2092 |
-
dependencies = [
|
| 2093 |
-
"windows-targets 0.53.5",
|
| 2094 |
-
]
|
| 2095 |
-
|
| 2096 |
-
[[package]]
|
| 2097 |
-
name = "windows-sys"
|
| 2098 |
-
version = "0.61.2"
|
| 2099 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2100 |
-
checksum = "ae137229bcbd6cdf0f7b80a31df61766145077ddf49416a728b02cb3921ff3fc"
|
| 2101 |
-
dependencies = [
|
| 2102 |
-
"windows-link",
|
| 2103 |
-
]
|
| 2104 |
-
|
| 2105 |
-
[[package]]
|
| 2106 |
-
name = "windows-targets"
|
| 2107 |
-
version = "0.48.5"
|
| 2108 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2109 |
-
checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c"
|
| 2110 |
-
dependencies = [
|
| 2111 |
-
"windows_aarch64_gnullvm 0.48.5",
|
| 2112 |
-
"windows_aarch64_msvc 0.48.5",
|
| 2113 |
-
"windows_i686_gnu 0.48.5",
|
| 2114 |
-
"windows_i686_msvc 0.48.5",
|
| 2115 |
-
"windows_x86_64_gnu 0.48.5",
|
| 2116 |
-
"windows_x86_64_gnullvm 0.48.5",
|
| 2117 |
-
"windows_x86_64_msvc 0.48.5",
|
| 2118 |
-
]
|
| 2119 |
-
|
| 2120 |
-
[[package]]
|
| 2121 |
-
name = "windows-targets"
|
| 2122 |
-
version = "0.52.6"
|
| 2123 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2124 |
-
checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973"
|
| 2125 |
-
dependencies = [
|
| 2126 |
-
"windows_aarch64_gnullvm 0.52.6",
|
| 2127 |
-
"windows_aarch64_msvc 0.52.6",
|
| 2128 |
-
"windows_i686_gnu 0.52.6",
|
| 2129 |
-
"windows_i686_gnullvm 0.52.6",
|
| 2130 |
-
"windows_i686_msvc 0.52.6",
|
| 2131 |
-
"windows_x86_64_gnu 0.52.6",
|
| 2132 |
-
"windows_x86_64_gnullvm 0.52.6",
|
| 2133 |
-
"windows_x86_64_msvc 0.52.6",
|
| 2134 |
-
]
|
| 2135 |
-
|
| 2136 |
-
[[package]]
|
| 2137 |
-
name = "windows-targets"
|
| 2138 |
-
version = "0.53.5"
|
| 2139 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2140 |
-
checksum = "4945f9f551b88e0d65f3db0bc25c33b8acea4d9e41163edf90dcd0b19f9069f3"
|
| 2141 |
-
dependencies = [
|
| 2142 |
-
"windows-link",
|
| 2143 |
-
"windows_aarch64_gnullvm 0.53.1",
|
| 2144 |
-
"windows_aarch64_msvc 0.53.1",
|
| 2145 |
-
"windows_i686_gnu 0.53.1",
|
| 2146 |
-
"windows_i686_gnullvm 0.53.1",
|
| 2147 |
-
"windows_i686_msvc 0.53.1",
|
| 2148 |
-
"windows_x86_64_gnu 0.53.1",
|
| 2149 |
-
"windows_x86_64_gnullvm 0.53.1",
|
| 2150 |
-
"windows_x86_64_msvc 0.53.1",
|
| 2151 |
-
]
|
| 2152 |
-
|
| 2153 |
-
[[package]]
|
| 2154 |
-
name = "windows_aarch64_gnullvm"
|
| 2155 |
-
version = "0.48.5"
|
| 2156 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2157 |
-
checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8"
|
| 2158 |
-
|
| 2159 |
-
[[package]]
|
| 2160 |
-
name = "windows_aarch64_gnullvm"
|
| 2161 |
-
version = "0.52.6"
|
| 2162 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2163 |
-
checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3"
|
| 2164 |
-
|
| 2165 |
-
[[package]]
|
| 2166 |
-
name = "windows_aarch64_gnullvm"
|
| 2167 |
-
version = "0.53.1"
|
| 2168 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2169 |
-
checksum = "a9d8416fa8b42f5c947f8482c43e7d89e73a173cead56d044f6a56104a6d1b53"
|
| 2170 |
-
|
| 2171 |
-
[[package]]
|
| 2172 |
-
name = "windows_aarch64_msvc"
|
| 2173 |
-
version = "0.48.5"
|
| 2174 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2175 |
-
checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc"
|
| 2176 |
-
|
| 2177 |
-
[[package]]
|
| 2178 |
-
name = "windows_aarch64_msvc"
|
| 2179 |
-
version = "0.52.6"
|
| 2180 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2181 |
-
checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469"
|
| 2182 |
-
|
| 2183 |
-
[[package]]
|
| 2184 |
-
name = "windows_aarch64_msvc"
|
| 2185 |
-
version = "0.53.1"
|
| 2186 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2187 |
-
checksum = "b9d782e804c2f632e395708e99a94275910eb9100b2114651e04744e9b125006"
|
| 2188 |
-
|
| 2189 |
-
[[package]]
|
| 2190 |
-
name = "windows_i686_gnu"
|
| 2191 |
-
version = "0.48.5"
|
| 2192 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2193 |
-
checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e"
|
| 2194 |
-
|
| 2195 |
-
[[package]]
|
| 2196 |
-
name = "windows_i686_gnu"
|
| 2197 |
-
version = "0.52.6"
|
| 2198 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2199 |
-
checksum = "8e9b5ad5ab802e97eb8e295ac6720e509ee4c243f69d781394014ebfe8bbfa0b"
|
| 2200 |
-
|
| 2201 |
-
[[package]]
|
| 2202 |
-
name = "windows_i686_gnu"
|
| 2203 |
-
version = "0.53.1"
|
| 2204 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2205 |
-
checksum = "960e6da069d81e09becb0ca57a65220ddff016ff2d6af6a223cf372a506593a3"
|
| 2206 |
-
|
| 2207 |
-
[[package]]
|
| 2208 |
-
name = "windows_i686_gnullvm"
|
| 2209 |
-
version = "0.52.6"
|
| 2210 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2211 |
-
checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66"
|
| 2212 |
-
|
| 2213 |
-
[[package]]
|
| 2214 |
-
name = "windows_i686_gnullvm"
|
| 2215 |
-
version = "0.53.1"
|
| 2216 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2217 |
-
checksum = "fa7359d10048f68ab8b09fa71c3daccfb0e9b559aed648a8f95469c27057180c"
|
| 2218 |
-
|
| 2219 |
-
[[package]]
|
| 2220 |
-
name = "windows_i686_msvc"
|
| 2221 |
-
version = "0.48.5"
|
| 2222 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2223 |
-
checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406"
|
| 2224 |
-
|
| 2225 |
-
[[package]]
|
| 2226 |
-
name = "windows_i686_msvc"
|
| 2227 |
-
version = "0.52.6"
|
| 2228 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2229 |
-
checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66"
|
| 2230 |
-
|
| 2231 |
-
[[package]]
|
| 2232 |
-
name = "windows_i686_msvc"
|
| 2233 |
-
version = "0.53.1"
|
| 2234 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2235 |
-
checksum = "1e7ac75179f18232fe9c285163565a57ef8d3c89254a30685b57d83a38d326c2"
|
| 2236 |
-
|
| 2237 |
-
[[package]]
|
| 2238 |
-
name = "windows_x86_64_gnu"
|
| 2239 |
-
version = "0.48.5"
|
| 2240 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2241 |
-
checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e"
|
| 2242 |
-
|
| 2243 |
-
[[package]]
|
| 2244 |
-
name = "windows_x86_64_gnu"
|
| 2245 |
-
version = "0.52.6"
|
| 2246 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2247 |
-
checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78"
|
| 2248 |
-
|
| 2249 |
-
[[package]]
|
| 2250 |
-
name = "windows_x86_64_gnu"
|
| 2251 |
-
version = "0.53.1"
|
| 2252 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2253 |
-
checksum = "9c3842cdd74a865a8066ab39c8a7a473c0778a3f29370b5fd6b4b9aa7df4a499"
|
| 2254 |
-
|
| 2255 |
-
[[package]]
|
| 2256 |
-
name = "windows_x86_64_gnullvm"
|
| 2257 |
-
version = "0.48.5"
|
| 2258 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2259 |
-
checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc"
|
| 2260 |
-
|
| 2261 |
-
[[package]]
|
| 2262 |
-
name = "windows_x86_64_gnullvm"
|
| 2263 |
-
version = "0.52.6"
|
| 2264 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2265 |
-
checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d"
|
| 2266 |
-
|
| 2267 |
-
[[package]]
|
| 2268 |
-
name = "windows_x86_64_gnullvm"
|
| 2269 |
-
version = "0.53.1"
|
| 2270 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2271 |
-
checksum = "0ffa179e2d07eee8ad8f57493436566c7cc30ac536a3379fdf008f47f6bb7ae1"
|
| 2272 |
-
|
| 2273 |
-
[[package]]
|
| 2274 |
-
name = "windows_x86_64_msvc"
|
| 2275 |
-
version = "0.48.5"
|
| 2276 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2277 |
-
checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538"
|
| 2278 |
-
|
| 2279 |
-
[[package]]
|
| 2280 |
-
name = "windows_x86_64_msvc"
|
| 2281 |
-
version = "0.52.6"
|
| 2282 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2283 |
-
checksum = "589f6da84c646204747d1270a2a5661ea66ed1cced2631d546fdfb155959f9ec"
|
| 2284 |
-
|
| 2285 |
-
[[package]]
|
| 2286 |
-
name = "windows_x86_64_msvc"
|
| 2287 |
-
version = "0.53.1"
|
| 2288 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2289 |
-
checksum = "d6bbff5f0aada427a1e5a6da5f1f98158182f26556f345ac9e04d36d0ebed650"
|
| 2290 |
-
|
| 2291 |
-
[[package]]
|
| 2292 |
-
name = "wit-bindgen"
|
| 2293 |
-
version = "0.57.1"
|
| 2294 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2295 |
-
checksum = "1ebf944e87a7c253233ad6766e082e3cd714b5d03812acc24c318f549614536e"
|
| 2296 |
-
|
| 2297 |
-
[[package]]
|
| 2298 |
-
name = "writeable"
|
| 2299 |
-
version = "0.6.3"
|
| 2300 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2301 |
-
checksum = "1ffae5123b2d3fc086436f8834ae3ab053a283cfac8fe0a0b8eaae044768a4c4"
|
| 2302 |
-
|
| 2303 |
-
[[package]]
|
| 2304 |
-
name = "yoke"
|
| 2305 |
-
version = "0.8.3"
|
| 2306 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2307 |
-
checksum = "709fe23a0424b6a435d82152b1bd3fdfb0833487d5fa90d05d42762a9891fef5"
|
| 2308 |
-
dependencies = [
|
| 2309 |
-
"stable_deref_trait",
|
| 2310 |
-
"yoke-derive",
|
| 2311 |
-
"zerofrom",
|
| 2312 |
-
]
|
| 2313 |
-
|
| 2314 |
-
[[package]]
|
| 2315 |
-
name = "yoke-derive"
|
| 2316 |
-
version = "0.8.2"
|
| 2317 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2318 |
-
checksum = "de844c262c8848816172cef550288e7dc6c7b7814b4ee56b3e1553f275f1858e"
|
| 2319 |
-
dependencies = [
|
| 2320 |
-
"proc-macro2",
|
| 2321 |
-
"quote",
|
| 2322 |
-
"syn",
|
| 2323 |
-
"synstructure",
|
| 2324 |
-
]
|
| 2325 |
-
|
| 2326 |
-
[[package]]
|
| 2327 |
-
name = "zerocopy"
|
| 2328 |
-
version = "0.8.52"
|
| 2329 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2330 |
-
checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f"
|
| 2331 |
-
dependencies = [
|
| 2332 |
-
"zerocopy-derive",
|
| 2333 |
-
]
|
| 2334 |
-
|
| 2335 |
-
[[package]]
|
| 2336 |
-
name = "zerocopy-derive"
|
| 2337 |
-
version = "0.8.52"
|
| 2338 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2339 |
-
checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930"
|
| 2340 |
-
dependencies = [
|
| 2341 |
-
"proc-macro2",
|
| 2342 |
-
"quote",
|
| 2343 |
-
"syn",
|
| 2344 |
-
]
|
| 2345 |
-
|
| 2346 |
-
[[package]]
|
| 2347 |
-
name = "zerofrom"
|
| 2348 |
-
version = "0.1.8"
|
| 2349 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2350 |
-
checksum = "0ec05a11813ea801ff6d75110ad09cd0824ddba17dfe17128ea0d5f68e6c5272"
|
| 2351 |
-
dependencies = [
|
| 2352 |
-
"zerofrom-derive",
|
| 2353 |
-
]
|
| 2354 |
-
|
| 2355 |
-
[[package]]
|
| 2356 |
-
name = "zerofrom-derive"
|
| 2357 |
-
version = "0.1.7"
|
| 2358 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2359 |
-
checksum = "11532158c46691caf0f2593ea8358fed6bbf68a0315e80aae9bd41fbade684a1"
|
| 2360 |
-
dependencies = [
|
| 2361 |
-
"proc-macro2",
|
| 2362 |
-
"quote",
|
| 2363 |
-
"syn",
|
| 2364 |
-
"synstructure",
|
| 2365 |
-
]
|
| 2366 |
-
|
| 2367 |
-
[[package]]
|
| 2368 |
-
name = "zeroize"
|
| 2369 |
-
version = "1.9.0"
|
| 2370 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2371 |
-
checksum = "e13c156562582aa81c60cb29407084cdb54c4164760106ab78e6c5b0858cf64e"
|
| 2372 |
-
|
| 2373 |
-
[[package]]
|
| 2374 |
-
name = "zerotrie"
|
| 2375 |
-
version = "0.2.4"
|
| 2376 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2377 |
-
checksum = "0f9152d31db0792fa83f70fb2f83148effb5c1f5b8c7686c3459e361d9bc20bf"
|
| 2378 |
-
dependencies = [
|
| 2379 |
-
"displaydoc",
|
| 2380 |
-
"yoke",
|
| 2381 |
-
"zerofrom",
|
| 2382 |
-
]
|
| 2383 |
-
|
| 2384 |
-
[[package]]
|
| 2385 |
-
name = "zerovec"
|
| 2386 |
-
version = "0.11.6"
|
| 2387 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2388 |
-
checksum = "90f911cbc359ab6af17377d242225f4d75119aec87ea711a880987b18cd7b239"
|
| 2389 |
-
dependencies = [
|
| 2390 |
-
"yoke",
|
| 2391 |
-
"zerofrom",
|
| 2392 |
-
"zerovec-derive",
|
| 2393 |
-
]
|
| 2394 |
-
|
| 2395 |
-
[[package]]
|
| 2396 |
-
name = "zerovec-derive"
|
| 2397 |
-
version = "0.11.3"
|
| 2398 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2399 |
-
checksum = "625dc425cab0dca6dc3c3319506e6593dcb08a9f387ea3b284dbd52a92c40555"
|
| 2400 |
-
dependencies = [
|
| 2401 |
-
"proc-macro2",
|
| 2402 |
-
"quote",
|
| 2403 |
-
"syn",
|
| 2404 |
-
]
|
| 2405 |
-
|
| 2406 |
-
[[package]]
|
| 2407 |
-
name = "zmij"
|
| 2408 |
-
version = "1.0.21"
|
| 2409 |
-
source = "registry+https://github.com/rust-lang/crates.io-index"
|
| 2410 |
-
checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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| 7 |
-
# PostgreSQL-backed auth integration tests need an isolated DATABASE_URL and
|
| 8 |
-
# are intentionally not part of the hermetic extractor unit-test target.
|
| 9 |
-
postgres-integration-tests = []
|
| 10 |
-
|
| 11 |
-
[dependencies]
|
| 12 |
-
async-trait = "0.1"
|
| 13 |
-
axum = "0.8"
|
| 14 |
-
base64 = "0.22"
|
| 15 |
-
clap = { version = "4", features = ["derive"] }
|
| 16 |
-
regex = "1"
|
| 17 |
-
reqwest = { version = "0.12", default-features = false, features = ["json", "rustls-tls", "socks"] }
|
| 18 |
-
serde = { version = "1", features = ["derive"] }
|
| 19 |
-
serde_json = "1"
|
| 20 |
-
sqlx = { version = "0.8", default-features = false, features = ["runtime-tokio-rustls", "postgres"] }
|
| 21 |
-
thiserror = "1"
|
| 22 |
-
tokio = { version = "1", features = ["macros", "rt-multi-thread", "sync", "time"] }
|
| 23 |
-
url = "2"
|
| 24 |
-
uuid = { version = "1", features = ["v4", "serde"] }
|
| 25 |
-
|
| 26 |
-
[dev-dependencies]
|
| 27 |
-
tempfile = "3"
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
Dockerfile
CHANGED
|
@@ -1,26 +1,78 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
|
| 4 |
-
|
| 5 |
-
|
| 6 |
-
COPY
|
| 7 |
-
|
| 8 |
-
|
| 9 |
-
|
| 10 |
-
|
| 11 |
-
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
# syntax=docker/dockerfile:1.7
|
| 2 |
+
|
| 3 |
+
# Stage 1: Build frontend assets once on the build platform.
|
| 4 |
+
FROM --platform=$BUILDPLATFORM node:20-bookworm-slim AS frontend-builder
|
| 5 |
+
WORKDIR /app
|
| 6 |
+
COPY frontend/package*.json ./
|
| 7 |
+
RUN npm ci
|
| 8 |
+
COPY frontend/ ./
|
| 9 |
+
RUN npm run build
|
| 10 |
+
|
| 11 |
+
# Stage 2: Runtime image.
|
| 12 |
+
FROM python:3.12-slim-bookworm
|
| 13 |
+
WORKDIR /workspace
|
| 14 |
+
|
| 15 |
+
ENV DEBIAN_FRONTEND=noninteractive \
|
| 16 |
+
PYTHONIOENCODING=utf-8 \
|
| 17 |
+
PYTHONUNBUFFERED=1 \
|
| 18 |
+
PYTHONDONTWRITEBYTECODE=1 \
|
| 19 |
+
PIP_NO_CACHE_DIR=1 \
|
| 20 |
+
PORT=7860 \
|
| 21 |
+
WORKERS=1 \
|
| 22 |
+
LOG_LEVEL=INFO \
|
| 23 |
+
PYTHONPATH=/workspace
|
| 24 |
+
|
| 25 |
+
RUN apt-get update && apt-get install -y --no-install-recommends \
|
| 26 |
+
ca-certificates \
|
| 27 |
+
curl \
|
| 28 |
+
wget \
|
| 29 |
+
libasound2 \
|
| 30 |
+
libatk-bridge2.0-0 \
|
| 31 |
+
libatk1.0-0 \
|
| 32 |
+
libcups2 \
|
| 33 |
+
libdbus-1-3 \
|
| 34 |
+
libdbus-glib-1-2 \
|
| 35 |
+
libdrm2 \
|
| 36 |
+
libgbm1 \
|
| 37 |
+
libglib2.0-0 \
|
| 38 |
+
libgtk-3-0 \
|
| 39 |
+
libnspr4 \
|
| 40 |
+
libnss3 \
|
| 41 |
+
libpangocairo-1.0-0 \
|
| 42 |
+
libpulse0 \
|
| 43 |
+
libx11-6 \
|
| 44 |
+
libx11-xcb1 \
|
| 45 |
+
libxcb1 \
|
| 46 |
+
libxcomposite1 \
|
| 47 |
+
libxdamage1 \
|
| 48 |
+
libxext6 \
|
| 49 |
+
libxfixes3 \
|
| 50 |
+
libxkbcommon0 \
|
| 51 |
+
libxrandr2 \
|
| 52 |
+
libxshmfence1 \
|
| 53 |
+
fonts-liberation \
|
| 54 |
+
fonts-noto-cjk \
|
| 55 |
+
&& rm -rf /var/lib/apt/lists/*
|
| 56 |
+
|
| 57 |
+
COPY backend/requirements.txt /tmp/requirements.txt
|
| 58 |
+
RUN pip install -r /tmp/requirements.txt
|
| 59 |
+
|
| 60 |
+
# HF Spaces runs the container as uid 1000; build runtime-writable assets as that user.
|
| 61 |
+
RUN useradd -m -u 1000 user && chown user:user /workspace
|
| 62 |
+
ENV HOME=/home/user
|
| 63 |
+
USER user
|
| 64 |
+
|
| 65 |
+
# Download Camoufox browser at build time so runtime hosts do not need to fetch it again.
|
| 66 |
+
RUN python -m camoufox fetch
|
| 67 |
+
|
| 68 |
+
COPY --chown=user:user backend/ ./backend/
|
| 69 |
+
COPY --chown=user:user start.py ./
|
| 70 |
+
COPY --from=frontend-builder --chown=user:user /app/dist ./frontend/dist
|
| 71 |
+
RUN mkdir -p /workspace/data /workspace/logs /workspace/frontend
|
| 72 |
+
|
| 73 |
+
EXPOSE 7860
|
| 74 |
+
|
| 75 |
+
HEALTHCHECK --interval=30s --timeout=10s --start-period=120s --retries=3 \
|
| 76 |
+
CMD curl -fsS "http://127.0.0.1:${PORT:-7860}/healthz" || exit 1
|
| 77 |
+
|
| 78 |
+
CMD ["sh", "-c", "python -m uvicorn backend.main:app --host 0.0.0.0 --port ${PORT:-7860} --workers ${WORKERS:-1}"]
|
README.md
CHANGED
|
@@ -1,144 +1,1226 @@
|
|
| 1 |
---
|
| 2 |
-
title:
|
| 3 |
-
emoji:
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
| 7 |
-
pinned: false
|
| 8 |
app_port: 7860
|
|
|
|
| 9 |
---
|
| 10 |
|
| 11 |
-
#
|
| 12 |
-
|
| 13 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 18 |
-
|
| 19 |
-
|
| 20 |
-
|
| 21 |
-
|
| 22 |
-
|
| 23 |
-
|
| 24 |
-
|
| 25 |
-
|
| 26 |
-
|
| 27 |
-
|
| 28 |
-
|
| 29 |
-
|
| 30 |
-
-
|
| 31 |
-
|
| 32 |
-
|
| 33 |
-
|
| 34 |
-
|
| 35 |
-
|
| 36 |
-
|
| 37 |
-
|
| 38 |
-
|
| 39 |
-
|
| 40 |
-
-
|
| 41 |
-
-
|
| 42 |
-
-
|
| 43 |
-
-
|
| 44 |
-
-
|
| 45 |
-
-
|
| 46 |
-
-
|
| 47 |
-
-
|
| 48 |
-
-
|
| 49 |
-
|
| 50 |
-
|
| 51 |
-
|
| 52 |
-
|
| 53 |
-
|
| 54 |
-
|
| 55 |
-
|
| 56 |
-
|
| 57 |
-
|
| 58 |
-
|
| 59 |
-
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
| 72 |
-
|
| 73 |
-
|
| 74 |
-
|
| 75 |
-
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 |
-
|
| 82 |
-
|
| 83 |
-
|
| 84 |
-
|
| 85 |
-
|
| 86 |
-
|
| 87 |
-
|
| 88 |
-
|
| 89 |
-
|
| 90 |
-
|
| 91 |
-
|
| 92 |
-
|
| 93 |
-
|
| 94 |
-
|
| 95 |
-
|
| 96 |
-
|
| 97 |
-
|
| 98 |
-
|
| 99 |
-
|
| 100 |
-
|
| 101 |
-
-
|
| 102 |
-
-
|
| 103 |
-
-
|
| 104 |
-
|
| 105 |
-
|
| 106 |
-
|
| 107 |
-
|
| 108 |
-
|
| 109 |
-
|
| 110 |
-
|
| 111 |
-
|
| 112 |
-
|
| 113 |
-
|
| 114 |
-
|
| 115 |
-
|
| 116 |
-
|
| 117 |
-
|
| 118 |
-
|
| 119 |
-
|
| 120 |
-
|
| 121 |
-
- `
|
| 122 |
-
-
|
| 123 |
-
|
| 124 |
-
|
| 125 |
-
|
| 126 |
-
|
| 127 |
-
|
| 128 |
-
-
|
| 129 |
-
-
|
| 130 |
-
-
|
| 131 |
-
-
|
| 132 |
-
-
|
| 133 |
-
|
| 134 |
-
-
|
| 135 |
-
|
| 136 |
-
##
|
| 137 |
-
|
| 138 |
-
-
|
| 139 |
-
-
|
| 140 |
-
-
|
| 141 |
-
-
|
| 142 |
-
-
|
| 143 |
-
-
|
| 144 |
-
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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|
| 3 |
+
emoji: "⚡"
|
| 4 |
colorFrom: blue
|
| 5 |
colorTo: indigo
|
| 6 |
sdk: docker
|
|
|
|
| 7 |
app_port: 7860
|
| 8 |
+
pinned: false
|
| 9 |
---
|
| 10 |
|
| 11 |
+
# qwen2API Enterprise Gateway
|
| 12 |
+
|
| 13 |
+
[](https://github.com/YuJunZhiXue/qwen2API/blob/main/LICENSE)
|
| 14 |
+
[](https://github.com/YuJunZhiXue/qwen2API/stargazers)
|
| 15 |
+
[](https://github.com/YuJunZhiXue/qwen2API/network/members)
|
| 16 |
+
[](https://github.com/YuJunZhiXue/qwen2API/releases)
|
| 17 |
+
[](https://hub.docker.com/r/yujunzhixue/qwen2api)
|
| 18 |
+
|
| 19 |
+
[](https://zeabur.com/templates/qwen2api)
|
| 20 |
+
[](https://vercel.com/new/clone?repository-url=https%3A%2F%2Fgithub.com%2FYuJunZhiXue%2Fqwen2API)
|
| 21 |
+
|
| 22 |
+
语言 / Language: [中文](./README.md) | [English](./README.en.md)
|
| 23 |
+
|
| 24 |
+
qwen2api 用于将通义千问(chat.qwen.ai)网页版能力转换为 OpenAI、Anthropic Claude 与 Gemini 兼容接口。项目后端基于 FastAPI,前端基于 React + Vite,内置管理台、账号池、工具调用解析、图片生成链路与多种部署方式。
|
| 25 |
+
|
| 26 |
+
---
|
| 27 |
+
|
| 28 |
+
## 目录
|
| 29 |
+
|
| 30 |
+
- [项目说明](#项目说明)
|
| 31 |
+
- [架构概览](#架构概览)
|
| 32 |
+
- [核心能力](#核心能力)
|
| 33 |
+
- [接口支持](#接口支持)
|
| 34 |
+
- [模型映射](#模型映射)
|
| 35 |
+
- [图片生成](#图片生成)
|
| 36 |
+
- [快速开始](#快速开始)
|
| 37 |
+
- [方式一:Docker 直接运行预构建镜像(推荐)](#方式一docker-直接运行预构建镜像推荐)
|
| 38 |
+
- [方式二:本地源码运行](#方式二本地源码运行)
|
| 39 |
+
- [环境变量说明(.env)](#环境变量说明env)
|
| 40 |
+
- [docker-compose.yml 说明](#docker-composeyml-说明)
|
| 41 |
+
- [端口说明](#端口说明)
|
| 42 |
+
- [WebUI 管理台](#webui-管理台)
|
| 43 |
+
- [数据持久化](#数据持久化)
|
| 44 |
+
- [项目目录结构](#项目目录结构)
|
| 45 |
+
- [高级特性与内部机制](#高级特性与内部机制)
|
| 46 |
+
- [性能优化与稳定性](#性能优化与稳定性)
|
| 47 |
+
- [客户端接入示例](#客户端接入示例)
|
| 48 |
+
- [常见问题](#常见问题)
|
| 49 |
+
- [故障排查速查表](#故障排查速查表)
|
| 50 |
+
- [开发指南](#开发指南)
|
| 51 |
+
- [变更日志与路线图](#变更日志与路线图)
|
| 52 |
+
- [许可证与免责声明](#许可证与免责声明)
|
| 53 |
+
|
| 54 |
+
---
|
| 55 |
+
|
| 56 |
+
## 项目说明
|
| 57 |
+
|
| 58 |
+
本项目提供以下能力:
|
| 59 |
+
|
| 60 |
+
1. 将千问网页对话能力转换为 OpenAI Chat Completions 接口。
|
| 61 |
+
2. 将千问网页对话能力转换为 Anthropic Messages 接口。
|
| 62 |
+
3. 将千问网页对话能力转换为 Gemini GenerateContent 接口。
|
| 63 |
+
4. 提供独立的图片生成接口 `POST /v1/images/generations`。
|
| 64 |
+
5. 支持工具调用(Tool Calling)与工具结果回传。
|
| 65 |
+
6. 提供管理台,用于账号管理、API Key 管理、图片生成测试与运行状态查看。
|
| 66 |
+
7. 提供多账号轮询、限流冷却、重试与浏览器 / httpx 混合引擎。
|
| 67 |
+
|
| 68 |
+
---
|
| 69 |
+
|
| 70 |
+
## 架构概览
|
| 71 |
+
|
| 72 |
+
```mermaid
|
| 73 |
+
flowchart LR
|
| 74 |
+
Client["🖥️ 客户端 / SDK\n(OpenAI / Claude / Gemini)"]
|
| 75 |
+
Upstream["☁️ chat.qwen.ai"]
|
| 76 |
+
|
| 77 |
+
subgraph qwen2API["qwen2API(FastAPI 统一网关)"]
|
| 78 |
+
Router["FastAPI Router + 中间件\n(CORS / Logging / Context)"]
|
| 79 |
+
|
| 80 |
+
subgraph Adapters["协议适配层"]
|
| 81 |
+
OA["OpenAI\n/v1/chat/completions"]
|
| 82 |
+
CA["Claude\n/anthropic/v1/messages"]
|
| 83 |
+
GA["Gemini\n/v1beta/models/*"]
|
| 84 |
+
IA["Images\n/v1/images/generations"]
|
| 85 |
+
FA["Files\n/v1/files"]
|
| 86 |
+
Admin["Admin API\n/api/admin/*"]
|
| 87 |
+
WebUI["WebUI\n/(静态托管)"]
|
| 88 |
+
end
|
| 89 |
+
|
| 90 |
+
subgraph Runtime["运行时核心能力"]
|
| 91 |
+
Bridge["协议转换桥\n(多协议 <-> 统一格式)"]
|
| 92 |
+
Executor["Qwen Executor\n(会话管理 + 流式处理)"]
|
| 93 |
+
Auth["Auth Resolver\n(API key / Bearer)"]
|
| 94 |
+
Pool["Account Pool\n(并发控制 + 限流冷却)"]
|
| 95 |
+
QwenClient["Qwen Client\n(HTTP / 浏览器自动化)"]
|
| 96 |
+
ToolParser["Tool Parser\n(工具调用解析)"]
|
| 97 |
+
FileStore["File Store\n(本地文件暂存)"]
|
| 98 |
+
end
|
| 99 |
+
end
|
| 100 |
+
|
| 101 |
+
Client --> Router
|
| 102 |
+
Router --> OA & CA & GA & IA & FA
|
| 103 |
+
Router --> Admin
|
| 104 |
+
Router --> WebUI
|
| 105 |
+
|
| 106 |
+
OA & CA & GA --> Bridge
|
| 107 |
+
Bridge --> Executor
|
| 108 |
+
Executor --> Auth
|
| 109 |
+
Executor -.账号轮询.-> Pool
|
| 110 |
+
Executor -.工具调用.-> ToolParser
|
| 111 |
+
IA & FA --> FileStore
|
| 112 |
+
Auth --> QwenClient
|
| 113 |
+
QwenClient --> Upstream
|
| 114 |
+
Upstream --> QwenClient
|
| 115 |
+
Executor --> Bridge
|
| 116 |
+
Bridge --> Client
|
| 117 |
+
```
|
| 118 |
+
|
| 119 |
+
**架构说明**:
|
| 120 |
+
|
| 121 |
+
- **后端**:Python FastAPI(`backend/`),统一处理多协议适配与上游调用
|
| 122 |
+
- **前端**:React 管理台(`frontend/`),运行时托管静态构建产物
|
| 123 |
+
- **部署**:Docker(推荐)、本地运行、Vercel、Zeabur
|
| 124 |
+
|
| 125 |
+
**核心特性**:
|
| 126 |
+
|
| 127 |
+
- **统一路由内核**:所有协议入口统一汇聚到 FastAPI Router,避免多入口行为漂移
|
| 128 |
+
- **协议转换桥**:Claude / Gemini 入口先转换为统一格式,再调用上游,最后转换回原协议响应
|
| 129 |
+
- **工具调用支持**:支持 OpenAI / Claude / Gemini 三种工具调用格式,自动解析与转换
|
| 130 |
+
- **账号池管理**:多账号轮询、并发控制、限流冷却、自动重试
|
| 131 |
+
- **文件附件**:支持文件上传、本地暂存、上下文注入
|
| 132 |
+
- **图片生成**:独立图片生成接口,支持多种尺寸比例
|
| 133 |
+
|
| 134 |
+
---
|
| 135 |
+
|
| 136 |
+
## 核心能力
|
| 137 |
+
|
| 138 |
+
- OpenAI / Anthropic / Gemini 三套接口兼容。
|
| 139 |
+
- 工具调用解析与工具结果回传。
|
| 140 |
+
- Browser Engine、Httpx Engine、Hybrid Engine 三种执行模式。
|
| 141 |
+
- 多账号并发池、动态冷却、故障重试。
|
| 142 |
+
- 基于千问网页真实工具链路的图片生成。
|
| 143 |
+
- WebUI 管理台。
|
| 144 |
+
- 健康检查与就绪检查接口。
|
| 145 |
+
- **Chat ID 预热池**:后台预建会话队列,单次请求节省 500ms~3s 握手耗时。
|
| 146 |
+
- **Schema 压缩**:JSON Schema → TypeScript-like 签名,tool prompt 节省 ~90% 空间。
|
| 147 |
+
- **工具名混淆**:客户端工具名自动加 `u_` 前缀或别名,避免 Qwen 内置函数校验拦截。
|
| 148 |
+
- **工具调用幻觉防护**:auto_agent_blocked、重复调用拦截、空响应重试、毒性拒绝识别。
|
| 149 |
+
- **截断自动续写**:`##TOOL_CALL##` 未闭合时自动续写并去重拼接。
|
| 150 |
+
- **文件内容缓存**:代理侧缓存 Claude Code 的"Unchanged since last read"真实内容。
|
| 151 |
+
- **历史拒绝清洗**:扫描历史 assistant 消息中的拒绝/自限文本,防止级联复现。
|
| 152 |
+
- **增量流式 warmup**:累积 96 字符再吐出,期间过滤道歉前缀和不完整工具调用。
|
| 153 |
+
- **话题隔离**:检测 user 消息的实体 Jaccard 相似度,判定新任务时自动丢弃无关历史。
|
| 154 |
+
- **工具少样本注入**:按命名空间挑代表工具构造合成 few-shot,提高 MCP / Skill 类工具命中率。
|
| 155 |
+
- **Edit/StrReplace 模糊匹配**:自动修复智能引号、空白、反斜杠差异导致的 exact match 失败。
|
| 156 |
+
- **CLIProxy 协议转换层**:多协议入口统一落到 `StandardRequest`,避免多入口行为漂移。
|
| 157 |
+
|
| 158 |
+
---
|
| 159 |
+
|
| 160 |
+
## 接口支持
|
| 161 |
+
|
| 162 |
+
| 接口类型 | 路径 | 说明 |
|
| 163 |
+
|---|---|---|
|
| 164 |
+
| OpenAI Chat | `POST /v1/chat/completions` | 支持流式与非流式、工具调用、图片意图自动识别 |
|
| 165 |
+
| OpenAI Models | `GET /v1/models` | 返回可用模型别名 |
|
| 166 |
+
| OpenAI Images | `POST /v1/images/generations` | 图片生成接口 |
|
| 167 |
+
| Anthropic Messages | `POST /anthropic/v1/messages` | Claude / Anthropic SDK 兼容 |
|
| 168 |
+
| Gemini GenerateContent | `POST /v1beta/models/{model}:generateContent` | Gemini SDK 兼容 |
|
| 169 |
+
| Gemini Stream | `POST /v1beta/models/{model}:streamGenerateContent` | 流式输出 |
|
| 170 |
+
| Admin API | `/api/admin/*` | 管理接口 |
|
| 171 |
+
| Health | `/healthz` | 存活探针 |
|
| 172 |
+
| Ready | `/readyz` | 就绪探针 |
|
| 173 |
+
|
| 174 |
+
---
|
| 175 |
+
|
| 176 |
+
## 模型映射
|
| 177 |
+
|
| 178 |
+
当前默认将主流客户端模型名称统一映射至 `qwen3.6-plus`。
|
| 179 |
+
|
| 180 |
+
| 传入模型名 | 实际调用 |
|
| 181 |
+
|---|---|
|
| 182 |
+
| `gpt-4o` / `gpt-4-turbo` / `gpt-4.1` / `o1` / `o3` | `qwen3.6-plus` |
|
| 183 |
+
| `gpt-4o-mini` / `gpt-3.5-turbo` | `qwen3.6-plus` |
|
| 184 |
+
| `claude-opus-4-6` / `claude-sonnet-4-6` / `claude-3-5-sonnet` | `qwen3.6-plus` |
|
| 185 |
+
| `claude-3-haiku` / `claude-haiku-4-5` | `qwen3.6-plus` |
|
| 186 |
+
| `gemini-2.5-pro` / `gemini-2.5-flash` / `gemini-1.5-pro` | `qwen3.6-plus` |
|
| 187 |
+
| `deepseek-chat` / `deepseek-reasoner` | `qwen3.6-plus` |
|
| 188 |
+
|
| 189 |
+
未命中映射表时,默认回退为传入模型名本身;若管理台设置了自定义映射规则,则以配置为准。
|
| 190 |
+
|
| 191 |
+
---
|
| 192 |
+
|
| 193 |
+
## 图片生成
|
| 194 |
+
|
| 195 |
+
qwen2API 提供与 OpenAI Images 接口兼容的图片生成能力。
|
| 196 |
+
|
| 197 |
+
- 接口:`POST /v1/images/generations`
|
| 198 |
+
- 默认模型别名:`dall-e-3`
|
| 199 |
+
- 实际底层:`qwen3.6-plus` + 千问网页 `image_gen` 工具
|
| 200 |
+
- 返回图片链接域名:通常为 `cdn.qwenlm.ai`
|
| 201 |
+
|
| 202 |
+
### 请求示例
|
| 203 |
+
|
| 204 |
+
```bash
|
| 205 |
+
curl http://127.0.0.1:7860/v1/images/generations \
|
| 206 |
+
-H "Content-Type: application/json" \
|
| 207 |
+
-H "Authorization: Bearer YOUR_API_KEY" \
|
| 208 |
+
-d '{
|
| 209 |
+
"model": "dall-e-3",
|
| 210 |
+
"prompt": "一只赛博朋克风格的猫,霓虹灯背景,超写实",
|
| 211 |
+
"n": 1,
|
| 212 |
+
"size": "1024x1024",
|
| 213 |
+
"response_format": "url"
|
| 214 |
+
}'
|
| 215 |
+
```
|
| 216 |
+
|
| 217 |
+
### 返回示例
|
| 218 |
+
|
| 219 |
+
```json
|
| 220 |
+
{
|
| 221 |
+
"created": 1712345678,
|
| 222 |
+
"data": [
|
| 223 |
+
{
|
| 224 |
+
"url": "https://cdn.qwenlm.ai/output/.../image.png?key=...",
|
| 225 |
+
"revised_prompt": "一只赛博朋克风格的猫,霓虹灯背景,超写实"
|
| 226 |
+
}
|
| 227 |
+
]
|
| 228 |
+
}
|
| 229 |
+
```
|
| 230 |
+
|
| 231 |
+
### 支持的图片比例
|
| 232 |
+
|
| 233 |
+
前端图片生成页面内置以下比例:
|
| 234 |
+
|
| 235 |
+
- `1:1`
|
| 236 |
+
- `16:9`
|
| 237 |
+
- `9:16`
|
| 238 |
+
- `4:3`
|
| 239 |
+
- `3:4`
|
| 240 |
+
|
| 241 |
+
### Chat 接口图片意图识别
|
| 242 |
+
|
| 243 |
+
`/v1/chat/completions` 支持根据用户消息自动识别图片生成意图。例如:
|
| 244 |
+
|
| 245 |
+
- “帮我画一张……”
|
| 246 |
+
- “生成一张图片……”
|
| 247 |
+
- “draw an image of ……”
|
| 248 |
+
|
| 249 |
+
当识别为图片生成请求时,系统会自动切换到图片生成管道。
|
| 250 |
+
|
| 251 |
+
---
|
| 252 |
+
|
| 253 |
+
## 快速开始
|
| 254 |
+
|
| 255 |
+
### 方式一:Docker 直接运行预构建镜像(推荐)
|
| 256 |
+
|
| 257 |
+
此方式适用于生产环境、测试服务器与普通部署场景。
|
| 258 |
+
优点是:**不需要本地编译前端,不需要在服务器构建镜像,不需要服务器自行下载 Camoufox。**
|
| 259 |
+
|
| 260 |
+
#### 第一步:准备目录
|
| 261 |
+
|
| 262 |
+
```bash
|
| 263 |
+
mkdir qwen2api && cd qwen2api
|
| 264 |
+
mkdir -p data logs
|
| 265 |
+
```
|
| 266 |
+
|
| 267 |
+
#### 第二步:创建 `docker-compose.yml`
|
| 268 |
+
|
| 269 |
+
```yaml
|
| 270 |
+
services:
|
| 271 |
+
qwen2api:
|
| 272 |
+
image: yujunzhixue/qwen2api:latest
|
| 273 |
+
container_name: qwen2api
|
| 274 |
+
restart: unless-stopped
|
| 275 |
+
env_file:
|
| 276 |
+
- path: .env
|
| 277 |
+
required: false
|
| 278 |
+
ports:
|
| 279 |
+
- "7860:7860"
|
| 280 |
+
volumes:
|
| 281 |
+
- ./data:/workspace/data
|
| 282 |
+
- ./logs:/workspace/logs
|
| 283 |
+
shm_size: '256m'
|
| 284 |
+
environment:
|
| 285 |
+
PYTHONIOENCODING: utf-8
|
| 286 |
+
PORT: "7860"
|
| 287 |
+
ENGINE_MODE: "hybrid"
|
| 288 |
+
healthcheck:
|
| 289 |
+
test: ["CMD", "curl", "-f", "http://localhost:7860/healthz"]
|
| 290 |
+
interval: 30s
|
| 291 |
+
timeout: 10s
|
| 292 |
+
start_period: 120s
|
| 293 |
+
retries: 3
|
| 294 |
+
```
|
| 295 |
+
|
| 296 |
+
#### 第三步:创建 `.env`(可选但推荐)
|
| 297 |
+
|
| 298 |
+
建议至少写入以下内容:
|
| 299 |
+
|
| 300 |
+
```env
|
| 301 |
+
# ========== 必须修改 ==========
|
| 302 |
+
ADMIN_KEY=change-me-now # 管理台登录密钥,必须修改为强密码!
|
| 303 |
+
|
| 304 |
+
# ========== 基础配置 ==========
|
| 305 |
+
PORT=7860 # 服务监听端口
|
| 306 |
+
WORKERS=1 # Uvicorn worker 数量,必须保持 1(多 worker 会导致 JSON 文件冲突)
|
| 307 |
+
LOG_LEVEL=INFO # 日志级别:DEBUG/INFO/WARNING/ERROR
|
| 308 |
+
|
| 309 |
+
# ========== 并发控制 ==========
|
| 310 |
+
MAX_INFLIGHT=1 # 每账号最大并发请求数(账号多时可改为 2)
|
| 311 |
+
MAX_RETRIES=3 # 请求失败最大重试次数(网络不稳定时增加到 5)
|
| 312 |
+
|
| 313 |
+
# ========== 限流冷却 ==========
|
| 314 |
+
ACCOUNT_MIN_INTERVAL_MS=1200 # 同账号两次请求最小间隔(毫秒),被限流时启用
|
| 315 |
+
REQUEST_JITTER_MIN_MS=120 # 请求前随机抖动最小值(毫秒)
|
| 316 |
+
REQUEST_JITTER_MAX_MS=360 # 请求前随机抖动最大值(毫秒)
|
| 317 |
+
RATE_LIMIT_BASE_COOLDOWN=600 # 限流基础冷却时间(秒),频繁限流时增加到 1200
|
| 318 |
+
RATE_LIMIT_MAX_COOLDOWN=3600 # 限流最大冷却时间(秒)
|
| 319 |
+
|
| 320 |
+
# ========== 数据文件路径(Docker 部署通常不需要改)==========
|
| 321 |
+
ACCOUNTS_FILE=/workspace/data/accounts.json
|
| 322 |
+
USERS_FILE=/workspace/data/users.json
|
| 323 |
+
CONTEXT_CACHE_FILE=/workspace/data/context_cache.json
|
| 324 |
+
UPLOADED_FILES_FILE=/workspace/data/uploaded_files.json
|
| 325 |
+
```
|
| 326 |
+
|
| 327 |
+
**环境变量详细说明**:
|
| 328 |
+
|
| 329 |
+
| 变量 | 默认值 | 说明 | 何时修改 |
|
| 330 |
+
|------|--------|------|----------|
|
| 331 |
+
| `ADMIN_KEY` | `admin` | 管理台登录密钥 | **必须修改**为强密码 |
|
| 332 |
+
| `PORT` | `7860` | 服务监听端口 | 端口冲突时修改 |
|
| 333 |
+
| `WORKERS` | `1` | Uvicorn worker 数量 | **必须保持 1**,多 worker 会导致数据冲突 |
|
| 334 |
+
| `LOG_LEVEL` | `INFO` | 日志级别 | 调试时改为 `DEBUG`,生产环境改为 `WARNING` |
|
| 335 |
+
| `MAX_INFLIGHT` | `1` | 每账号最大并发数 | 账号多且稳定时可改为 `2` |
|
| 336 |
+
| `MAX_RETRIES` | `3` | 请求失败重试次数 | 网络不稳定时增加到 `5` |
|
| 337 |
+
| `ACCOUNT_MIN_INTERVAL_MS` | `0` | 同账号请求间隔(毫秒) | 被限流时改为 `1200` |
|
| 338 |
+
| `REQUEST_JITTER_MIN_MS` | `0` | 请求抖动最小值 | 模拟真实用户行为时设置 `120` |
|
| 339 |
+
| `REQUEST_JITTER_MAX_MS` | `0` | 请求抖动最大值 | 模拟真实用户行为时设置 `360` |
|
| 340 |
+
| `RATE_LIMIT_BASE_COOLDOWN` | `600` | 限流冷却时间(秒) | 频繁限流时增加到 `1200` |
|
| 341 |
+
|
| 342 |
+
**docker-compose.yml 配置说明**:
|
| 343 |
+
|
| 344 |
+
| 配置项 | 说明 | 建议修改 |
|
| 345 |
+
|--------|------|----------|
|
| 346 |
+
| `image` | 预构建镜像地址,支持 amd64/arm64 | 保持默认 `yujunzhixue/qwen2api:latest` |
|
| 347 |
+
| `ports` | 端口映射,格式:`宿主机端口:容器端口` | 如 7860 被占用,改为 `"8080:7860"` |
|
| 348 |
+
| `volumes` | 数据持久化挂载 | **必须保留**,否则重启后数据丢失 |
|
| 349 |
+
| `shm_size` | 浏览器共享内存 | 浏览器崩溃时改为 `"512m"` |
|
| 350 |
+
| `environment.PORT` | 容器内服务端口 | 通常不需要改 |
|
| 351 |
+
| `healthcheck` | 健康检查配置 | 保持默认即可 |
|
| 352 |
+
|
| 353 |
+
#### 第四步:启动服务
|
| 354 |
+
|
| 355 |
+
```bash
|
| 356 |
+
docker compose up -d
|
| 357 |
+
```
|
| 358 |
+
|
| 359 |
+
#### 第五步:查看状态
|
| 360 |
+
|
| 361 |
+
```bash
|
| 362 |
+
docker compose ps
|
| 363 |
+
docker compose logs -f
|
| 364 |
+
curl http://127.0.0.1:7860/healthz
|
| 365 |
+
```
|
| 366 |
+
|
| 367 |
+
#### 第六步:更新服务
|
| 368 |
+
|
| 369 |
+
```bash
|
| 370 |
+
docker compose pull
|
| 371 |
+
docker compose up -d
|
| 372 |
+
```
|
| 373 |
+
|
| 374 |
+
---
|
| 375 |
+
|
| 376 |
+
## 跨平台(amd64/arm64)部署说明
|
| 377 |
+
|
| 378 |
+
你在 Mac(Apple Silicon, arm64)上 `docker build` 默认会产出 `linux/arm64` 镜像;
|
| 379 |
+
如果把这个单架构镜像推到仓库,Linux x86_64 服务器(`linux/amd64`)拉取后会报:
|
| 380 |
+
|
| 381 |
+
`The requested image's platform (linux/arm64/v8) does not match the detected host platform (linux/amd64/...)`
|
| 382 |
+
|
| 383 |
+
正确做法是发布 **多架构镜像(manifest list)**,同时包含 `linux/amd64` 与 `linux/arm64`。
|
| 384 |
+
|
| 385 |
+
### 方案 A:用 GitHub Actions 自动发布多架构镜像(推荐)
|
| 386 |
+
|
| 387 |
+
本仓库已在 [docker-publish.yml](file:///Users/hongyan/work/workspace/todo/ai/qwen2API/.github/workflows/docker-publish.yml) 配置 `platforms: linux/amd64,linux/arm64`。
|
| 388 |
+
你只需要把修复推到你自己的仓库并设置 DockerHub secrets,然后在服务器端执行:
|
| 389 |
+
|
| 390 |
+
```bash
|
| 391 |
+
docker compose pull
|
| 392 |
+
docker compose up -d
|
| 393 |
+
```
|
| 394 |
+
|
| 395 |
+
### 方案 B:本地 buildx 推多架构镜像(适合无 CI 的场景)
|
| 396 |
+
|
| 397 |
+
```bash
|
| 398 |
+
# 1) 登录镜像仓库(DockerHub/ACR/GHCR 任意)
|
| 399 |
+
docker login
|
| 400 |
+
|
| 401 |
+
# 2) 构建并推送多架构镜像
|
| 402 |
+
./scripts/buildx-push.sh <你的仓库名>/qwen2api:<tag>
|
| 403 |
+
```
|
| 404 |
+
|
| 405 |
+
服务器端仍然只需要 `docker compose pull && docker compose up -d`。
|
| 406 |
+
|
| 407 |
+
### 关于 docker-compose 文件
|
| 408 |
+
|
| 409 |
+
生产部署(Linux/Windows)建议使用拉镜像模式:
|
| 410 |
+
|
| 411 |
+
- `docker-compose.yml`:默认 `image: yujunzhixue/qwen2api:latest`(或通过 `QWEN2API_IMAGE` 覆盖)
|
| 412 |
+
- `docker-compose.build.yml`:仅用于本地从源码构建(开发/调试)
|
| 413 |
+
|
| 414 |
+
---
|
| 415 |
+
|
| 416 |
+
### 方式二:本地源码运行
|
| 417 |
+
|
| 418 |
+
此方式适用于本地开发与调试。
|
| 419 |
+
|
| 420 |
+
#### 环境要求
|
| 421 |
+
|
| 422 |
+
- Python 3.12+
|
| 423 |
+
- Node.js 20+
|
| 424 |
+
- 可访问 Camoufox 下载源
|
| 425 |
+
|
| 426 |
+
#### 步骤
|
| 427 |
+
|
| 428 |
+
```bash
|
| 429 |
+
git clone https://github.com/YuJunZhiXue/qwen2API.git
|
| 430 |
+
cd qwen2API
|
| 431 |
+
python start.py
|
| 432 |
+
```
|
| 433 |
+
|
| 434 |
+
`python start.py` 会自动完成以下工作:
|
| 435 |
+
|
| 436 |
+
1. 安装后端依赖
|
| 437 |
+
2. 下载 Camoufox 浏览器内核
|
| 438 |
+
3. 安装前端依赖
|
| 439 |
+
4. 构建前端
|
| 440 |
+
5. 启动后端服务
|
| 441 |
+
|
| 442 |
+
---
|
| 443 |
+
|
| 444 |
+
## 环境变量说明(.env)
|
| 445 |
+
|
| 446 |
+
项目提供 `.env.example` 作为模板。以下为主要参数说明。
|
| 447 |
+
|
| 448 |
+
### 基础参数
|
| 449 |
+
|
| 450 |
+
| 参数 | 默认值 | 说明 |
|
| 451 |
+
|---|---|---|
|
| 452 |
+
| `ADMIN_KEY` | `change-me-now` / `admin` | 管理台管理员密钥。建议部署后立即修改。 |
|
| 453 |
+
| `PORT` | `7860` | 后端服务监听端口。 |
|
| 454 |
+
| `WORKERS` | `1` 或 `3` | Uvicorn worker 数量。单实例环境建议 1。 |
|
| 455 |
+
| `REGISTER_SECRET` | 空 | 用户注册密钥。为空时表示不限制注册。 |
|
| 456 |
+
|
| 457 |
+
### 引擎参数
|
| 458 |
+
|
| 459 |
+
| 参数 | 默认值 | 说明 |
|
| 460 |
+
|---|---|---|
|
| 461 |
+
| `ENGINE_MODE` | `hybrid` | 引擎模式。可选 `hybrid`、`httpx`、`browser`。 |
|
| 462 |
+
| `BROWSER_POOL_SIZE` | `2` | 浏览器页面池大小。值越大并发越高,但内存占用也越高。 |
|
| 463 |
+
| `STREAM_KEEPALIVE_INTERVAL` | `5` | 流式输出 keepalive 间隔。 |
|
| 464 |
+
|
| 465 |
+
#### `ENGINE_MODE` 说明
|
| 466 |
+
|
| 467 |
+
- `hybrid`:推荐模式。聊天、建会话、删会话优先走浏览器;httpx 作为故障兜底。
|
| 468 |
+
- `httpx`:全部优先走 httpx / curl_cffi。速度更快,但浏览器特征更弱,适合对速度优先的测试场景。
|
| 469 |
+
- `browser`:全部走浏览器。更接近真实网页环境,但资源占用更高。
|
| 470 |
+
|
| 471 |
+
如果需要在 `httpx` 和 `hybrid` 之间切换,只需修改:
|
| 472 |
+
|
| 473 |
+
```env
|
| 474 |
+
ENGINE_MODE=httpx
|
| 475 |
+
```
|
| 476 |
+
|
| 477 |
+
或:
|
| 478 |
+
|
| 479 |
+
```env
|
| 480 |
+
ENGINE_MODE=hybrid
|
| 481 |
+
```
|
| 482 |
+
|
| 483 |
+
修改后重启服务:
|
| 484 |
+
|
| 485 |
+
```bash
|
| 486 |
+
docker compose restart
|
| 487 |
+
```
|
| 488 |
+
|
| 489 |
+
### 并发与风控参数
|
| 490 |
+
|
| 491 |
+
| 参数 | 默认值 | 说明 |
|
| 492 |
+
|---|---|---|
|
| 493 |
+
| `MAX_INFLIGHT` | `1` | 每个账号允许的最大并发请求数。 |
|
| 494 |
+
| `ACCOUNT_MIN_INTERVAL_MS` | `1200` | 同一账号两次请求之间的最小间隔。 |
|
| 495 |
+
| `REQUEST_JITTER_MIN_MS` | `120` | 随机抖动最小值。 |
|
| 496 |
+
| `REQUEST_JITTER_MAX_MS` | `360` | 随机抖动最大值。 |
|
| 497 |
+
| `MAX_RETRIES` | `2` | 请求失败最大重试次数。 |
|
| 498 |
+
| `TOOL_MAX_RETRIES` | `2` | 工具调用相关最大重试次数。 |
|
| 499 |
+
| `EMPTY_RESPONSE_RETRIES` | `1` | 空响应最大重试次数。 |
|
| 500 |
+
| `RATE_LIMIT_BASE_COOLDOWN` | `600` | 账号限流基础冷却时间(秒)。 |
|
| 501 |
+
| `RATE_LIMIT_MAX_COOLDOWN` | `3600` | 账号限流最大冷却时间(秒)。 |
|
| 502 |
+
|
| 503 |
+
### 数据路径参数
|
| 504 |
+
|
| 505 |
+
| 参数 | 默认值 | 说明 |
|
| 506 |
+
|---|---|---|
|
| 507 |
+
| `ACCOUNTS_FILE` | `/workspace/data/accounts.json` | 账号数据文件路径。 |
|
| 508 |
+
| `USERS_FILE` | `/workspace/data/users.json` | API Key / 用户数据文件路径。 |
|
| 509 |
+
| `CAPTURES_FILE` | `/workspace/data/captures.json` | 抓取结果文件路径。 |
|
| 510 |
+
| `CONFIG_FILE` | `/workspace/data/config.json` | 运行时配置文件路径。 |
|
| 511 |
+
|
| 512 |
+
---
|
| 513 |
+
|
| 514 |
+
## docker-compose.yml 说明
|
| 515 |
+
|
| 516 |
+
以下是推荐的 Compose 配置:
|
| 517 |
+
|
| 518 |
+
```yaml
|
| 519 |
+
services:
|
| 520 |
+
qwen2api:
|
| 521 |
+
image: yujunzhixue/qwen2api:latest
|
| 522 |
+
container_name: qwen2api
|
| 523 |
+
restart: unless-stopped
|
| 524 |
+
env_file:
|
| 525 |
+
- path: .env
|
| 526 |
+
required: false
|
| 527 |
+
ports:
|
| 528 |
+
- "7860:7860"
|
| 529 |
+
volumes:
|
| 530 |
+
- ./data:/workspace/data
|
| 531 |
+
- ./logs:/workspace/logs
|
| 532 |
+
shm_size: '256m'
|
| 533 |
+
environment:
|
| 534 |
+
PYTHONIOENCODING: utf-8
|
| 535 |
+
PORT: "7860"
|
| 536 |
+
ENGINE_MODE: "hybrid"
|
| 537 |
+
healthcheck:
|
| 538 |
+
test: ["CMD", "curl", "-f", "http://localhost:7860/healthz"]
|
| 539 |
+
interval: 30s
|
| 540 |
+
timeout: 10s
|
| 541 |
+
start_period: 120s
|
| 542 |
+
retries: 3
|
| 543 |
+
```
|
| 544 |
+
|
| 545 |
+
### 字段说明
|
| 546 |
+
|
| 547 |
+
| 字段 | 说明 |
|
| 548 |
+
|---|---|
|
| 549 |
+
| `image` | 预构建镜像地址。普通部署推荐使用。 |
|
| 550 |
+
| `container_name` | 容器名称。 |
|
| 551 |
+
| `restart` | 开机或故障时自动重启。 |
|
| 552 |
+
| `env_file` | 从 `.env` 加载环境变量。 |
|
| 553 |
+
| `ports` | 将宿主机端口映射到容器端口。 |
|
| 554 |
+
| `volumes` | 持久化数据与日志目录。 |
|
| 555 |
+
| `shm_size` | 浏览器共享内存。Camoufox / Firefox 运行建议至少 256m。 |
|
| 556 |
+
| `environment` | Compose 中直接写入的环境变量,优先级高于镜像默认值。 |
|
| 557 |
+
| `healthcheck` | 容器健康检查。 |
|
| 558 |
+
|
| 559 |
+
### 用户需要修改的部分
|
| 560 |
+
|
| 561 |
+
通常只需要根据部署环境修改以下内容:
|
| 562 |
+
|
| 563 |
+
1. **端口映射**
|
| 564 |
+
```yaml
|
| 565 |
+
ports:
|
| 566 |
+
- "7860:7860"
|
| 567 |
+
```
|
| 568 |
+
如果服务器 7860 已占用,可以改为:
|
| 569 |
+
```yaml
|
| 570 |
+
ports:
|
| 571 |
+
- "8080:7860"
|
| 572 |
+
```
|
| 573 |
+
|
| 574 |
+
2. **引擎模式**
|
| 575 |
+
```yaml
|
| 576 |
+
environment:
|
| 577 |
+
ENGINE_MODE: "hybrid"
|
| 578 |
+
```
|
| 579 |
+
可改为:
|
| 580 |
+
```yaml
|
| 581 |
+
environment:
|
| 582 |
+
ENGINE_MODE: "httpx"
|
| 583 |
+
```
|
| 584 |
+
|
| 585 |
+
3. **共享内存**
|
| 586 |
+
```yaml
|
| 587 |
+
shm_size: '256m'
|
| 588 |
+
```
|
| 589 |
+
如果浏览器容易崩溃,可改为:
|
| 590 |
+
```yaml
|
| 591 |
+
shm_size: '512m'
|
| 592 |
+
```
|
| 593 |
+
|
| 594 |
+
4. **数据挂载目录**
|
| 595 |
+
```yaml
|
| 596 |
+
volumes:
|
| 597 |
+
- ./data:/workspace/data
|
| 598 |
+
- ./logs:/workspace/logs
|
| 599 |
+
```
|
| 600 |
+
如需自定义存储路径,可替换左侧宿主机目录。
|
| 601 |
+
|
| 602 |
+
---
|
| 603 |
+
|
| 604 |
+
## 端口说明
|
| 605 |
+
|
| 606 |
+
### 为什么 Docker 部署前后端在同一个端口
|
| 607 |
+
|
| 608 |
+
Docker 镜像中已经构建好前端静态文件,并由后端统一托管:
|
| 609 |
+
|
| 610 |
+
- 后端 API:`http://host:7860/*`
|
| 611 |
+
- 前端管理台:`http://host:7860/`
|
| 612 |
+
|
| 613 |
+
因此 **Docker 部署时默认只有一个端口 7860**。
|
| 614 |
+
|
| 615 |
+
### 为什么本地开发时可能不是同一个端口
|
| 616 |
+
|
| 617 |
+
本地开发通常有两种方式:
|
| 618 |
+
|
| 619 |
+
1. **使用 `python start.py`**
|
| 620 |
+
前端会先构建为静态文件,再由后端统一托管。此时通常仍是一个端口。
|
| 621 |
+
|
| 622 |
+
2. **使用前端 Vite 开发服务器单独运行**
|
| 623 |
+
例如:
|
| 624 |
+
- 前端:`http://localhost:5173`
|
| 625 |
+
- 后端:`http://localhost:7860`
|
| 626 |
+
|
| 627 |
+
这种模式仅用于前端开发调试,不是生产部署模式。
|
| 628 |
+
|
| 629 |
+
---
|
| 630 |
+
|
| 631 |
+
## WebUI 管理台
|
| 632 |
+
|
| 633 |
+
管理台默认由后端托管,入口为:
|
| 634 |
+
|
| 635 |
+
```text
|
| 636 |
+
http://127.0.0.1:7860/
|
| 637 |
+
```
|
| 638 |
+
|
| 639 |
+
主要页面包括:
|
| 640 |
+
|
| 641 |
+
| 页面 | 说明 |
|
| 642 |
+
|---|---|
|
| 643 |
+
| 运行状态 | 查看整体服务状态、引擎状态与统计信息 |
|
| 644 |
+
| 账号管理 | 添加、测试、禁用、查看上游账���状态 |
|
| 645 |
+
| API Key | 管理下游调用密钥 |
|
| 646 |
+
| 接口测试 | 直接测试 OpenAI 对话接口 |
|
| 647 |
+
| 图片生成 | 图形化图片生成页面 |
|
| 648 |
+
| 系统设置 | 查看并修改部分运行时参数 |
|
| 649 |
+
|
| 650 |
+
---
|
| 651 |
+
|
| 652 |
+
## 数据持久化
|
| 653 |
+
|
| 654 |
+
默认数据目录:
|
| 655 |
+
|
| 656 |
+
- `data/accounts.json`:上游账号信息
|
| 657 |
+
- `data/users.json`:下游 API Key / 用户数据
|
| 658 |
+
- `data/captures.json`:抓取结果
|
| 659 |
+
- `data/config.json`:运行时配置
|
| 660 |
+
- `logs/`:运行日志
|
| 661 |
+
|
| 662 |
+
生产环境请务必持久化 `data/` 与 `logs/`。
|
| 663 |
+
|
| 664 |
+
---
|
| 665 |
+
|
| 666 |
+
## 项目目录结构
|
| 667 |
+
|
| 668 |
+
```text
|
| 669 |
+
qwen2API/
|
| 670 |
+
├── backend/ # Python FastAPI 后端
|
| 671 |
+
│ ├── main.py # 应用入口,注册路由 / 中间件 / 生命周期
|
| 672 |
+
│ ├── api/ # 协议入口层
|
| 673 |
+
│ │ ├── chat.py # OpenAI Chat Completions
|
| 674 |
+
│ │ ├── anthropic.py # Anthropic Messages
|
| 675 |
+
│ │ ├── gemini.py # Gemini GenerateContent
|
| 676 |
+
│ │ ├── images.py # 图片生成
|
| 677 |
+
│ │ ├── files.py # 文件上传 / 管理
|
| 678 |
+
│ │ ├── admin.py # 管理 API
|
| 679 |
+
│ │ └── models.py # 模型别名
|
| 680 |
+
│ ├── adapter/
|
| 681 |
+
│ │ ├── cli_proxy.py # 多协议 → StandardRequest 转换代理
|
| 682 |
+
│ │ └── standard_request.py # 统一请求结构 + 客户端 profile
|
| 683 |
+
│ ├── core/
|
| 684 |
+
│ │ ├── config.py # 全局配置 / 模型映射
|
| 685 |
+
│ │ ├── request_logging.py # 请求上下文 + 链路日志
|
| 686 |
+
│ │ ├── auth.py # API Key / Bearer 鉴权
|
| 687 |
+
│ │ └── account_pool/ # 账号池(已拆分为子模块)
|
| 688 |
+
│ │ ├── pool_core.py # 池状态 / 冷却 / 淘汰
|
| 689 |
+
│ │ └── pool_acquire.py # 账号获取 / 并发控制
|
| 690 |
+
│ ├── runtime/
|
| 691 |
+
│ │ ├── execution.py # 流式执行 + 重试指令
|
| 692 |
+
│ │ └── stream_metrics.py # 流式指标埋点
|
| 693 |
+
│ ├── services/ # 稳定性 / 格式转换 / 兼容层
|
| 694 |
+
│ │ ├── qwen_client.py # HTTP + 浏览器双引擎
|
| 695 |
+
│ │ ├── prompt_builder.py # 消息 → prompt + tools 装配
|
| 696 |
+
│ │ ├── tool_parser.py # ##TOOL_CALL## 文本协议解析
|
| 697 |
+
│ │ ├── tool_validator.py # 工具入参校验
|
| 698 |
+
│ │ ├── tool_arg_fixer.py # 智能引号 / 模糊 Edit 修复
|
| 699 |
+
│ │ ├── tool_few_shot.py # 按命名空间注入少样本
|
| 700 |
+
│ │ ├── tool_name_obfuscation.py# 工具名混淆避免 Qwen 函数校验
|
| 701 |
+
│ │ ├── schema_compressor.py # JSON Schema → TS-like 签名
|
| 702 |
+
│ │ ├── chat_id_pool.py # chat_id 预热池
|
| 703 |
+
│ │ ├── file_content_cache.py # Read 结果缓存
|
| 704 |
+
│ │ ├── incremental_text_streamer.py # 流式 warmup / guard
|
| 705 |
+
│ │ ├── refusal_cleaner.py # 历史拒绝文本清洗
|
| 706 |
+
│ │ ├── topic_isolation.py # 新任务检测 / 历史切分
|
| 707 |
+
│ │ ├── truncation_recovery.py # ##TOOL_CALL## 截断续写
|
| 708 |
+
│ │ ├── openai_stream_translator.py # 文本协议 → OpenAI SSE
|
| 709 |
+
│ │ ├── context_attachment_manager.py # 长上下文 → 附件
|
| 710 |
+
│ │ ├── context_offload.py # 上下文卸载策略
|
| 711 |
+
│ │ ├── context_cleanup.py # TTL 清理
|
| 712 |
+
│ │ ├── auth_resolver.py # API Key → 上游账号
|
| 713 |
+
│ │ ├── auth_quota.py # 下游 Key 配额
|
| 714 |
+
│ │ ├── completion_bridge.py # 多协议响应桥
|
| 715 |
+
│ │ ├── file_store.py # 本地文件暂存
|
| 716 |
+
│ │ ├── upstream_file_uploader.py # 文件上传至千问
|
| 717 |
+
│ │ ├── garbage_collector.py # 会话 / 临时文件 GC
|
| 718 |
+
│ │ ├── response_formatters.py # 各协议响应格式化
|
| 719 |
+
│ │ ├── standard_request_builder.py
|
| 720 |
+
│ │ ├── attachment_preprocessor.py
|
| 721 |
+
│ │ ├── task_session.py
|
| 722 |
+
│ │ └── token_calc.py
|
| 723 |
+
│ ├── toolcall/
|
| 724 |
+
│ │ ├── normalize.py # 工具名规范化
|
| 725 |
+
│ │ ├── stream_state.py # 流式工具调用状态机
|
| 726 |
+
│ │ └── formats_json.py # JSON 工具格式
|
| 727 |
+
│ ├── upstream/
|
| 728 |
+
│ │ └── qwen_executor.py # 会话生命周期 + 流式分发
|
| 729 |
+
│ └── data/ # 运行期可写目录(accounts/users/config/...)
|
| 730 |
+
├── frontend/ # React + Vite 管理台
|
| 731 |
+
│ ├── src/
|
| 732 |
+
│ │ ├── pages/ # Dashboard / Settings / Test / Images
|
| 733 |
+
│ │ ├── layouts/
|
| 734 |
+
│ │ └── components/
|
| 735 |
+
│ └── vite.config.ts
|
| 736 |
+
├── docker-compose.yml
|
| 737 |
+
├── Dockerfile
|
| 738 |
+
├── start.py # 一键启动(装依赖 + 下浏览器 + 构建前端)
|
| 739 |
+
├── requirements.txt
|
| 740 |
+
├── .env.example
|
| 741 |
+
└── README.md
|
| 742 |
+
```
|
| 743 |
+
|
| 744 |
+
---
|
| 745 |
+
|
| 746 |
+
## 高级特性与内部机制
|
| 747 |
+
|
| 748 |
+
以下是 qwen2API 为了在"千问网页对话"这条弱约束上游上跑稳定工具调用而引入的内部模块。普通使用者可以忽略;希望深度定制或贡献代码时可参考。
|
| 749 |
+
|
| 750 |
+
### Chat ID 预热池(`chat_id_pool.py`)
|
| 751 |
+
|
| 752 |
+
- **动机**:`/api/v2/chats/new` 握手耗时在健康时 500ms,抖动时可达 5~6s。
|
| 753 |
+
- **做法**:服务启动后为每个可用账号预建 `target_per_account` 个 `chat_id`,请求到来直接 pop;用掉一个后台立即补位。
|
| 754 |
+
- **TTL**:单条 `chat_id` 默认 30 分钟过期,过期则丢弃重建。
|
| 755 |
+
- **兜底**:取不到预热 chat_id 时 fallback 到同步 `create_chat`。
|
| 756 |
+
|
| 757 |
+
### Schema 压缩(`schema_compressor.py`)
|
| 758 |
+
|
| 759 |
+
把 JSON Schema 压缩成 TS-like 签名:
|
| 760 |
+
|
| 761 |
+
```
|
| 762 |
+
输入:{"type":"object","properties":{
|
| 763 |
+
"file_path":{"type":"string"},
|
| 764 |
+
"encoding":{"type":"string","enum":["utf-8","base64"]}},
|
| 765 |
+
"required":["file_path"]}
|
| 766 |
+
|
| 767 |
+
输出:{file_path!: string, encoding?: utf-8|base64}
|
| 768 |
+
```
|
| 769 |
+
|
| 770 |
+
- 单工具定义从 ~1.5KB 降到 ~150~250 bytes。90 个工具 ~135KB → ~15KB。
|
| 771 |
+
- 输入越小,上游输出预算越多,截断率越低。
|
| 772 |
+
|
| 773 |
+
### 工具名混淆(`tool_name_obfuscation.py`)
|
| 774 |
+
|
| 775 |
+
Qwen 上游会把常见短名(Read/Write/Bash/Edit…)当内置函数校验并返回"Tool X does not exists."。
|
| 776 |
+
|
| 777 |
+
- **显式别名**:`Read→fs_open_file`、`Bash→shell_run`、`Grep→text_search` 等。
|
| 778 |
+
- **通用兜底**:其余客户端工具自动加 `u_` 前缀,如 `TaskCreate→u_TaskCreate`、`mcp__playwright__click→u_mcp__playwright__click`。
|
| 779 |
+
- 出站(发往 Qwen)自动转换;入站(Qwen 返回)反向还原给客户端。
|
| 780 |
+
|
| 781 |
+
### 工具调用少样本(`tool_few_shot.py`)
|
| 782 |
+
|
| 783 |
+
- **问题**:有 90+ 工具(含 MCP / Skills / Plugin 多命名空间)时,Qwen 倾向于只调用几个"熟悉"的核心工具,MCP / Skill 几乎不被主动使用。
|
| 784 |
+
- **做法**:按命名空间分组挑一个代表工具,构造一条合成的 `[user → assistant]` 对话,assistant 示范**多种类型工具同时被调用**(1 个核心 + 最多 4 个第三方代表)。
|
| 785 |
+
- **效果**:模型看到"assistant 在第一步就用了 5 种不同类型的工具",会复现这种多样性。
|
| 786 |
+
|
| 787 |
+
### 工具调用截断续写(`truncation_recovery.py`)
|
| 788 |
+
|
| 789 |
+
- 检测:`##TOOL_CALL##` 开标签数 > `##END_CALL##` 闭标签数 → 说明某个 action block 尚未闭合。
|
| 790 |
+
- 续写:丢弃全部工具定义和历史(省 token),只保留末尾 2000 字节作为 anchor,在 assistant 角色塞入 anchor + user "请从中断点继续,不要重复"。
|
| 791 |
+
- 去重:`deduplicateContinuation` 去掉与已有末尾的重叠;最多续写 `MAX_AUTO_CONTINUE` 次。
|
| 792 |
+
|
| 793 |
+
### 文件内容缓存(`file_content_cache.py`)
|
| 794 |
+
|
| 795 |
+
Claude Code 客户端对同一文件重复 Read 时,不重发完整内容,只发一句 "File unchanged since last read" 提示语。但 qwen2API 每次请求都新建 Qwen chat,Qwen 完全没历史,提示语毫无意义。
|
| 796 |
+
|
| 797 |
+
- 在代理侧按 `(api_key, file_path)` 保留最近一次真实 Read 结果
|
| 798 |
+
- 检测到提示语时用缓存回填
|
| 799 |
+
- 内存 LRU,最多 200 条,每条 TTL 15 分钟,按 API KEY 做 session 隔离
|
| 800 |
+
|
| 801 |
+
### 历史拒绝清洗(`refusal_cleaner.py`)
|
| 802 |
+
|
| 803 |
+
扫描过往 assistant 消息里的拒绝 / 自我限制文本("I'm sorry, I cannot help..."、"我只能回答编程相关问题"、"Tool X does not exist"),命中后把整条消息内容替换为占位工具调用,防止模型看到自己的拒绝模式并级联复现。
|
| 804 |
+
|
| 805 |
+
### 增量流式 warmup(`incremental_text_streamer.py`)
|
| 806 |
+
|
| 807 |
+
- **warmup**:累积 96 字符再开始输出。期间可做拒绝检测 / 格式判断。
|
| 808 |
+
- **guard**:任何时候输出到客户端时都保留末尾 256 字符暂不输出,给跨 chunk 检测留空间(例如识别 `##TOOL_CALL##` 开始标记)。
|
| 809 |
+
- **finish()**:结束时把剩余全部补齐。
|
| 810 |
+
|
| 811 |
+
### 话题隔离(`topic_isolation.py`)
|
| 812 |
+
|
| 813 |
+
- 抽取每条 user 消息的**关键实体**:文件路径、URL、专名 / 引号字符串 / 驼峰标识符。
|
| 814 |
+
- 计算最新 user 消息实体集 vs 历史 first user 实体集的 **Jaccard 相似度**。
|
| 815 |
+
- 当最新 user 有自己的非空实体集且 Jaccard < 0.1 → 判定为新任务 → 调用方丢弃历史。
|
| 816 |
+
- 避免用户从"读文件"转到"浏览器注册"时,旧工具调用历史误导模型。
|
| 817 |
+
|
| 818 |
+
### 工具参数模糊修复(`tool_arg_fixer.py`)
|
| 819 |
+
|
| 820 |
+
- **smart quote 替换**:`" " ' '` → ASCII `" '`。
|
| 821 |
+
- **Edit / StrReplace 模糊匹配**:old_string 不 exact match 时,构造 fuzzy 正则(容忍引号 / 空白 / 反斜杠)在文件里搜,唯一命中则用真实文本替换 args 里的 old_string。
|
| 822 |
+
|
| 823 |
+
### 账号池子模块化(`core/account_pool/`)
|
| 824 |
+
|
| 825 |
+
原先的 `account_pool.py` 已拆分:
|
| 826 |
+
|
| 827 |
+
- `pool_core.py`:池状态 / 冷却 / 淘汰策略
|
| 828 |
+
- `pool_acquire.py`:并发控制 + 账号获取(MAX_INFLIGHT + MIN_INTERVAL + jitter)
|
| 829 |
+
|
| 830 |
+
老文件 `account_pool_old.py` 保留仅作参考,不再引用。
|
| 831 |
+
|
| 832 |
+
### CLIProxy 协议转换层(`adapter/cli_proxy.py`)
|
| 833 |
+
|
| 834 |
+
多协议入口(OpenAI / Claude / Gemini)统一通过 `CLIProxy.from_openai` / `from_anthropic` / `from_gemini` 落到 `StandardRequest`,避免三个入口各自维护 prompt 组装 / tool 装配 / client_profile 判定逻辑导致行为漂移。
|
| 835 |
+
|
| 836 |
+
### 运行期重试指令(`runtime/execution.py`)
|
| 837 |
+
|
| 838 |
+
集中式重试决策,支持以下触发原因:
|
| 839 |
+
|
| 840 |
+
| 原因 | 条件 | 处理 |
|
| 841 |
+
|---|---|---|
|
| 842 |
+
| `blocked_tool_name` | 命中已知被 Qwen 校验拦截的工具名 | 注入格式提醒 |
|
| 843 |
+
| `invalid_textual_tool_contract` | `##TOOL_CALL##` 格式错误 | 注入格式示例 |
|
| 844 |
+
| `repeated_same_tool` | 相同工具 + 相同参数重复调用 | 注入反复调用禁令 |
|
| 845 |
+
| `unchanged_read_result` | 刚收到 "Unchanged since last read" 又要 Read 同一文件 | 强制换工具 |
|
| 846 |
+
| `auto_agent_blocked` | 用户未提及 agent 却自动调 Agent | 强制不调 Agent |
|
| 847 |
+
| `search_no_results` | 上次 WebSearch 无结果又搜同样词 | 强制换工具 |
|
| 848 |
+
| `empty_upstream_response` | 上游返回空 | 换账号 + 换 chat_id 重试 |
|
| 849 |
+
| `toxic_refusal_early` | 流式早期识别到拒绝/幻觉 | 提前拦截 + 重试 |
|
| 850 |
+
|
| 851 |
+
---
|
| 852 |
+
|
| 853 |
+
## 性能优化与稳定性
|
| 854 |
+
|
| 855 |
+
### Hybrid 流式模式
|
| 856 |
+
|
| 857 |
+
工具调用采用缓冲模式(10~30s 等完整解析),纯文本采用实时流式(首 token ~5s)。既避免流式中途吐出不完整 `##TOOL_CALL##` 被客户端解析失败,又保证聊天场景的首 token 响应速度。
|
| 858 |
+
|
| 859 |
+
### 浏览器优先路由
|
| 860 |
+
|
| 861 |
+
生产部署默认 `ENGINE_MODE=hybrid`:
|
| 862 |
+
|
| 863 |
+
- **聊天 / 建会话 / 删会话**:优先走浏览器(Camoufox),拟态更高,限流风险低。
|
| 864 |
+
- **故障兜底**:浏览器失败时自动降级到 httpx / curl_cffi。
|
| 865 |
+
- 避免全 httpx 方案的账号封禁风险。
|
| 866 |
+
|
| 867 |
+
### 预热与池化
|
| 868 |
+
|
| 869 |
+
| 池 | 作用 | 命中后节省 |
|
| 870 |
+
|---|---|---|
|
| 871 |
+
| 账号池 | 多账号轮询 | 一次请求 0 握手 |
|
| 872 |
+
| Chat ID 预热池 | 预建会话 | 500ms~6s |
|
| 873 |
+
| 浏览器页面池 | 预开 Camoufox 页面 | 浏览器冷启动 3~10s |
|
| 874 |
+
|
| 875 |
+
### 限流冷却策略
|
| 876 |
+
|
| 877 |
+
账号命中 429 / 风控时:
|
| 878 |
+
|
| 879 |
+
- **基础冷却**:`RATE_LIMIT_BASE_COOLDOWN`(默认 600s)
|
| 880 |
+
- **指数退避**:连续触发冷却时翻倍,上限 `RATE_LIMIT_MAX_COOLDOWN`(默认 3600s)
|
| 881 |
+
- **冷却期自动跳过**:池获取账号时自动过滤冷却中的账号
|
| 882 |
+
|
| 883 |
+
### 请求抖动
|
| 884 |
+
|
| 885 |
+
`REQUEST_JITTER_MIN_MS` / `REQUEST_JITTER_MAX_MS` 会在每次请求前引入随机延迟,避免成百上千个请求在同一时刻打到上游导致同时限流。
|
| 886 |
+
|
| 887 |
+
---
|
| 888 |
+
|
| 889 |
+
## 客户端接入示例
|
| 890 |
+
|
| 891 |
+
### OpenAI Python SDK
|
| 892 |
+
|
| 893 |
+
```python
|
| 894 |
+
from openai import OpenAI
|
| 895 |
+
|
| 896 |
+
client = OpenAI(
|
| 897 |
+
base_url="http://127.0.0.1:7860/v1",
|
| 898 |
+
api_key="YOUR_API_KEY",
|
| 899 |
+
)
|
| 900 |
+
|
| 901 |
+
resp = client.chat.completions.create(
|
| 902 |
+
model="gpt-4o",
|
| 903 |
+
messages=[{"role": "user", "content": "你好"}],
|
| 904 |
+
stream=False,
|
| 905 |
+
)
|
| 906 |
+
print(resp.choices[0].message.content)
|
| 907 |
+
```
|
| 908 |
+
|
| 909 |
+
### Anthropic Python SDK(Claude Code / Anthropic SDK 通用)
|
| 910 |
+
|
| 911 |
+
```python
|
| 912 |
+
from anthropic import Anthropic
|
| 913 |
+
|
| 914 |
+
client = Anthropic(
|
| 915 |
+
base_url="http://127.0.0.1:7860/anthropic",
|
| 916 |
+
api_key="YOUR_API_KEY",
|
| 917 |
+
)
|
| 918 |
+
|
| 919 |
+
resp = client.messages.create(
|
| 920 |
+
model="claude-sonnet-4-6",
|
| 921 |
+
max_tokens=1024,
|
| 922 |
+
messages=[{"role": "user", "content": "你好"}],
|
| 923 |
+
)
|
| 924 |
+
print(resp.content[0].text)
|
| 925 |
+
```
|
| 926 |
+
|
| 927 |
+
### Claude Code CLI
|
| 928 |
+
|
| 929 |
+
在 `~/.claude/settings.json` 写入:
|
| 930 |
+
|
| 931 |
+
```json
|
| 932 |
+
{
|
| 933 |
+
"apiKey": "YOUR_API_KEY",
|
| 934 |
+
"apiUrl": "http://127.0.0.1:7860/anthropic"
|
| 935 |
+
}
|
| 936 |
+
```
|
| 937 |
+
|
| 938 |
+
或设置环境变量:
|
| 939 |
+
|
| 940 |
+
```bash
|
| 941 |
+
export ANTHROPIC_BASE_URL=http://127.0.0.1:7860/anthropic
|
| 942 |
+
export ANTHROPIC_API_KEY=YOUR_API_KEY
|
| 943 |
+
claude
|
| 944 |
+
```
|
| 945 |
+
|
| 946 |
+
### Google Gen AI Python SDK(Gemini)
|
| 947 |
+
|
| 948 |
+
```python
|
| 949 |
+
from google import genai
|
| 950 |
+
|
| 951 |
+
client = genai.Client(
|
| 952 |
+
api_key="YOUR_API_KEY",
|
| 953 |
+
http_options={"base_url": "http://127.0.0.1:7860"},
|
| 954 |
+
)
|
| 955 |
+
|
| 956 |
+
resp = client.models.generate_content(
|
| 957 |
+
model="gemini-2.5-pro",
|
| 958 |
+
contents="你好",
|
| 959 |
+
)
|
| 960 |
+
print(resp.text)
|
| 961 |
+
```
|
| 962 |
+
|
| 963 |
+
### curl 直接调用
|
| 964 |
+
|
| 965 |
+
```bash
|
| 966 |
+
# OpenAI 风格
|
| 967 |
+
curl http://127.0.0.1:7860/v1/chat/completions \
|
| 968 |
+
-H "Content-Type: application/json" \
|
| 969 |
+
-H "Authorization: Bearer YOUR_API_KEY" \
|
| 970 |
+
-d '{
|
| 971 |
+
"model": "gpt-4o",
|
| 972 |
+
"messages": [{"role": "user", "content": "你好"}],
|
| 973 |
+
"stream": true
|
| 974 |
+
}'
|
| 975 |
+
|
| 976 |
+
# Anthropic 风格
|
| 977 |
+
curl http://127.0.0.1:7860/anthropic/v1/messages \
|
| 978 |
+
-H "Content-Type: application/json" \
|
| 979 |
+
-H "x-api-key: YOUR_API_KEY" \
|
| 980 |
+
-H "anthropic-version: 2023-06-01" \
|
| 981 |
+
-d '{
|
| 982 |
+
"model": "claude-sonnet-4-6",
|
| 983 |
+
"max_tokens": 1024,
|
| 984 |
+
"messages": [{"role": "user", "content": "你好"}]
|
| 985 |
+
}'
|
| 986 |
+
```
|
| 987 |
+
|
| 988 |
+
---
|
| 989 |
+
|
| 990 |
+
## 常见问题
|
| 991 |
+
|
| 992 |
+
### 1. `.env` 不存在会怎样
|
| 993 |
+
|
| 994 |
+
如果 Compose 版本支持:
|
| 995 |
+
|
| 996 |
+
```yaml
|
| 997 |
+
env_file:
|
| 998 |
+
- path: .env
|
| 999 |
+
required: false
|
| 1000 |
+
```
|
| 1001 |
+
|
| 1002 |
+
则 `.env` 不存在时仍可启动,使用镜像默认配置。
|
| 1003 |
+
但正式部署建议始终创建 `.env`,至少设置 `ADMIN_KEY`。
|
| 1004 |
+
|
| 1005 |
+
### 2. 服务器无法下载 Camoufox
|
| 1006 |
+
|
| 1007 |
+
请使用“Docker 直接运行预构建镜像”方式。
|
| 1008 |
+
该方式不依赖服务器下载浏览器内核,也不需要服务器本地构建镜像。
|
| 1009 |
+
|
| 1010 |
+
### 3. 图片生成返回 500 或 no URL found
|
| 1011 |
+
|
| 1012 |
+
排查步骤:
|
| 1013 |
+
|
| 1014 |
+
1. 确认上游账号在网页中可正常使用图片生成。
|
| 1015 |
+
2. 查看日志中的 `[T2I]` 与 `[T2I-SSE]` 输出。
|
| 1016 |
+
3. 确认部署的是最新镜像版本。
|
| 1017 |
+
4. 确认前端页面未缓存旧资源。
|
| 1018 |
+
|
| 1019 |
+
### 4. `ENGINE_MODE` 选哪个
|
| 1020 |
+
|
| 1021 |
+
- 优先稳定性:`hybrid`
|
| 1022 |
+
- 优先速度:`httpx`
|
| 1023 |
+
- 优先网页拟态:`browser`
|
| 1024 |
+
|
| 1025 |
+
生产场景默认建议使用 `hybrid`。
|
| 1026 |
+
|
| 1027 |
+
### 5. 为什么工具调用偶尔被拦截成 "Tool X does not exists."
|
| 1028 |
+
|
| 1029 |
+
Qwen 上游会把常见短名(Read/Write/Bash...)当内置函数校验。qwen2API 已通过 `tool_name_obfuscation.py` 对全量工具名做别名 / `u_` 前缀处理。如果仍出现:
|
| 1030 |
+
|
| 1031 |
+
- 确认没有把旧版自定义 prompt 覆盖掉默认 prompt。
|
| 1032 |
+
- 提 issue 并附上 `prompt 前 500 字预览` 日志。
|
| 1033 |
+
|
| 1034 |
+
### 6. 大文件 Edit / Write 报 JSON 解析失败
|
| 1035 |
+
|
| 1036 |
+
通常是上游输出被 `max_output_tokens` 截断。`truncation_recovery.py` 已经内置"检测 + 续写 + 去重"链路,偶发失败可增加 `MAX_AUTO_CONTINUE` 或缩短一次要改的范围。
|
| 1037 |
+
|
| 1038 |
+
### 7. Claude Code 调子 agent 报 "Agent type 'xxx' not found"
|
| 1039 |
+
|
| 1040 |
+
Qwen 偶尔会对 `Agent` 工具的 `subagent_type` 生成客户端不认识的值(如 `"browser"`)。检查:
|
| 1041 |
+
|
| 1042 |
+
- 客户端 Claude Code 实际支持的 agent 列表(`/help` 或 Claude Code 设置里)。
|
| 1043 |
+
- 服务端日志是否出现 `auto_agent_blocked` 重试记录;若已流出再重试只能影响下一轮。
|
| 1044 |
+
- 必要时在 `prompt_builder.py` 里**移除**对 Agent 工具的暴露,或在 `openai_stream_translator.py` 做 enum 合法化。
|
| 1045 |
+
|
| 1046 |
+
### 8. 账号被限流 / 冷却太频繁
|
| 1047 |
+
|
| 1048 |
+
- 增加 `ACCOUNT_MIN_INTERVAL_MS`(例如 `1500~2000`)降低单账号频率。
|
| 1049 |
+
- 提高 `RATE_LIMIT_BASE_COOLDOWN`(例如 `1200`)让冷却期更长,避免立刻再被限。
|
| 1050 |
+
- 增加账号池大小(管理台 → 账号管理 → 添加账号)。
|
| 1051 |
+
|
| 1052 |
+
### 9. WebUI 登录后立刻被登出
|
| 1053 |
+
|
| 1054 |
+
- 确认 `ADMIN_KEY` 未在运行期被修改。
|
| 1055 |
+
- 清理浏览器 cookie / localStorage 后重试。
|
| 1056 |
+
- 确认不是多 worker 跑起来(`WORKERS=1`),多 worker 会导致 session 文件写冲突。
|
| 1057 |
+
|
| 1058 |
+
### 10. 前端页面白屏 / 静态资源 404
|
| 1059 |
+
|
| 1060 |
+
- 确认使用的是预构建镜像(`yujunzhixue/qwen2api:latest`),不是空壳镜像。
|
| 1061 |
+
- 本地源码运行时确保 `python start.py` 已完成前端构建。
|
| 1062 |
+
- 检查浏览器是否缓存了旧版本 HTML,强刷(Ctrl+Shift+R)。
|
| 1063 |
+
|
| 1064 |
+
---
|
| 1065 |
+
|
| 1066 |
+
## 故障排查速查表
|
| 1067 |
+
|
| 1068 |
+
| 现象 | 可能原因 | 排查步骤 |
|
| 1069 |
+
|------|----------|----------|
|
| 1070 |
+
| 启动即 OOM | 浏览器页面池过大或 `shm_size` 太小 | 降低 `BROWSER_POOL_SIZE`;`shm_size: '512m'` |
|
| 1071 |
+
| 首 token 超过 30s | 上游抖动 / 账号冷启动 | 看日志 `首个事件耗时`;开启 chat_id 预热池 |
|
| 1072 |
+
| 响应总是空字符串 | 上游返回空(`empty_upstream_response`) | 检查账号是否被限流;换账号重试 |
|
| 1073 |
+
| 工具调用被截成纯文本流给客户端 | 流出过早,未等 `##END_CALL##` | 检查是否错误开启了非 hybrid 模式;查看 `incremental_text_streamer` 日志 |
|
| 1074 |
+
| 连续 Read 同一文件 | 客户端发 "Unchanged since last read";服务端未回填缓存 | 看 `file_content_cache` 是否命中;确认 api_key 一致 |
|
| 1075 |
+
| 模型只会 Read/Write,MCP 工具不被调 | few-shot 未注入 | 确认 `[少样本] 注入 5 个代表` 日志出现 |
|
| 1076 |
+
| `Tool X does not exists.` | 工具名未被混淆 | 确认 `tool_name_obfuscation.to_qwen_name` 被调用 |
|
| 1077 |
+
| Agent subagent_type 报错 | Qwen 幻觉生成不存在的 agent | 参考常见问题 #7 |
|
| 1078 |
+
| `/healthz` 返回 200,但 `/readyz` 500 | 账号池未加载或浏览器未就绪 | 看管理台账号列表;延长 `start_period` |
|
| 1079 |
+
| 日志只有 prewarmed 没有新请求 | 客户端未打到 7860,或鉴权失败 | `curl -v http://127.0.0.1:7860/v1/models -H "Authorization: Bearer XXX"` |
|
| 1080 |
+
|
| 1081 |
+
### 日志关键字速查
|
| 1082 |
+
|
| 1083 |
+
| 关键字 | 含义 |
|
| 1084 |
+
|--------|------|
|
| 1085 |
+
| `[CLIProxy]` | 协议转换入口,含 `prompt_len` / `tools` 数 |
|
| 1086 |
+
| `[上游]` | 与 chat.qwen.ai 的交互,含账号 / chat_id / 耗时 |
|
| 1087 |
+
| `[ChatIdPool]` | chat_id 预热池状态 |
|
| 1088 |
+
| `[SessionPlan]` | 会话复用决策 |
|
| 1089 |
+
| `[少样本]` | few-shot 注入情况 |
|
| 1090 |
+
| `[Collect]` | 流式收集器检测到工具调用 |
|
| 1091 |
+
| `[收集完成]` | 本次响应的最终状态(字数 / 工具调用 / finish_reason) |
|
| 1092 |
+
| `[ToolDirective]` | 工具调用块 / stop_reason 决策 |
|
| 1093 |
+
| `[重试]` | 运行期重试原因 |
|
| 1094 |
+
| `[ContextCleanup]` | TTL 清理 |
|
| 1095 |
+
|
| 1096 |
+
---
|
| 1097 |
+
|
| 1098 |
+
## 开发指南
|
| 1099 |
+
|
| 1100 |
+
### 本地开发环境
|
| 1101 |
+
|
| 1102 |
+
```bash
|
| 1103 |
+
# 后端
|
| 1104 |
+
python -m venv .venv
|
| 1105 |
+
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
| 1106 |
+
pip install -r backend/requirements.txt
|
| 1107 |
+
uvicorn backend.main:app --reload --port 7860
|
| 1108 |
+
|
| 1109 |
+
# 前端(另开终端)
|
| 1110 |
+
cd frontend
|
| 1111 |
+
npm install
|
| 1112 |
+
npm run dev # http://localhost:5173
|
| 1113 |
+
```
|
| 1114 |
+
|
| 1115 |
+
前端开发模式下 API 默认代理到 `http://localhost:7860`,见 `frontend/vite.config.ts`。
|
| 1116 |
+
|
| 1117 |
+
### 代码结构约定
|
| 1118 |
+
|
| 1119 |
+
- **协议入口**:只做协议解析,调 `CLIProxy` 转 `StandardRequest` 后交给 `qwen_executor`。
|
| 1120 |
+
- **业务逻辑**:放 `services/` 下的独立模块,不要写进 API 层。
|
| 1121 |
+
- **运行期决策**:重试 / 拦截 / 续写等集中在 `runtime/execution.py`。
|
| 1122 |
+
- **工具调用**:文本协议解析在 `services/tool_parser.py`,状态机在 `toolcall/stream_state.py`。
|
| 1123 |
+
|
| 1124 |
+
### 调试建议
|
| 1125 |
+
|
| 1126 |
+
| 场景 | 打开方式 |
|
| 1127 |
+
|------|----------|
|
| 1128 |
+
| 看 prompt 全貌 | `LOG_LEVEL=DEBUG`,grep `prompt 前 500 字预览` |
|
| 1129 |
+
| 看流式每个 chunk | `LOG_LEVEL=DEBUG`,grep `[Collect]` |
|
| 1130 |
+
| 看账号选择 | grep `[上游] 账号已获取` |
|
| 1131 |
+
| 看重试 | grep `[重试]` 或 `auto_agent_blocked` |
|
| 1132 |
+
| 看 chat_id 池 | grep `[ChatIdPool]` |
|
| 1133 |
+
| 看 few-shot | grep `[少样本]` |
|
| 1134 |
+
|
| 1135 |
+
### 增加新的上游模型别名
|
| 1136 |
+
|
| 1137 |
+
在 `backend/core/config.py` 的 `MODEL_ALIAS_MAP` 里加一行:
|
| 1138 |
+
|
| 1139 |
+
```python
|
| 1140 |
+
MODEL_ALIAS_MAP = {
|
| 1141 |
+
...
|
| 1142 |
+
"my-custom-model": "qwen3.6-plus",
|
| 1143 |
+
}
|
| 1144 |
+
```
|
| 1145 |
+
|
| 1146 |
+
或通过管理台 → 系统设置 → 模型映射 动态配置(热生效,不需重启)。
|
| 1147 |
+
|
| 1148 |
+
### 增加客户端 profile
|
| 1149 |
+
|
| 1150 |
+
不同客户端(Claude Code / Cursor / Codex / Cline ...)对 tool 协议略有差异。新客户端需要:
|
| 1151 |
+
|
| 1152 |
+
1. 在 `backend/adapter/standard_request.py` 定义 profile 常量。
|
| 1153 |
+
2. 在 `backend/services/prompt_builder.py` 的 profile 分支里加入对应 prompt 模板。
|
| 1154 |
+
3. 在 `backend/services/openai_stream_translator.py` 处理该 profile 的输出 quirks。
|
| 1155 |
+
|
| 1156 |
+
### 运行单元测试
|
| 1157 |
+
|
| 1158 |
+
```bash
|
| 1159 |
+
pytest backend/tests -v
|
| 1160 |
+
```
|
| 1161 |
+
|
| 1162 |
+
(项目后续会补齐 services 层单测;当前以真实 API 冒烟为主。)
|
| 1163 |
+
|
| 1164 |
+
### 贡献流程
|
| 1165 |
+
|
| 1166 |
+
1. Fork 仓库并拉取 feature 分支。
|
| 1167 |
+
2. 保持单个 PR 聚焦一件事。
|
| 1168 |
+
3. 如果改动涉及上游协议或 prompt 模板,**附 2~3 条真实上游日志**作为佐证。
|
| 1169 |
+
4. 不建议在 PR 里混 lint 整理(diff 噪声大)。
|
| 1170 |
+
5. 欢迎提 issue 描述场景 + 日志片段,维护者会评估后分流。
|
| 1171 |
+
|
| 1172 |
+
---
|
| 1173 |
+
|
| 1174 |
+
## 变更日志与路线图
|
| 1175 |
+
|
| 1176 |
+
### 已完成
|
| 1177 |
+
|
| 1178 |
+
- [x] OpenAI / Anthropic / Gemini 三协议统一适配
|
| 1179 |
+
- [x] Browser / Httpx / Hybrid 三引擎 + 故障兜底
|
| 1180 |
+
- [x] 账号池 + 限流冷却 + 抖动
|
| 1181 |
+
- [x] Chat ID 预热池
|
| 1182 |
+
- [x] 浏览器页面池
|
| 1183 |
+
- [x] 文件上传 + 附件注入
|
| 1184 |
+
- [x] 图片生成(`/v1/images/generations`)
|
| 1185 |
+
- [x] 工具名混淆避免 Qwen 内置函数拦截
|
| 1186 |
+
- [x] Schema 压缩 + 少样本注入
|
| 1187 |
+
- [x] 截断自动续写 + 去重
|
| 1188 |
+
- [x] 文件内容缓存 + 话题隔离
|
| 1189 |
+
- [x] 历史拒绝清洗
|
| 1190 |
+
- [x] 增量流式 warmup / guard
|
| 1191 |
+
- [x] 运行期重试指令集中决策
|
| 1192 |
+
- [x] WebUI:账号管理 / API Key / 接口测试 / 图片生成 / 系统设置
|
| 1193 |
+
|
| 1194 |
+
### 计划中
|
| 1195 |
+
|
| 1196 |
+
- [ ] Agent 工具 `subagent_type` 的 enum 合法化兜底
|
| 1197 |
+
- [ ] 工具调用缓冲下发(避免早期幻觉参数流给客户端)
|
| 1198 |
+
- [ ] services 层单元测试覆盖
|
| 1199 |
+
- [ ] Prometheus 指标导出
|
| 1200 |
+
- [ ] 多后端模型(豆包 / 智谱等)并行接入作为故障兜底
|
| 1201 |
+
- [ ] WebUI 日志查看 / 账号健康监控看板
|
| 1202 |
+
|
| 1203 |
+
> 若你有强需求,欢迎在 issue 里 +1 推高优先级。
|
| 1204 |
+
|
| 1205 |
+
---
|
| 1206 |
+
|
| 1207 |
+
## 许可证与免责声明
|
| 1208 |
+
|
| 1209 |
+
### 开源许可证
|
| 1210 |
+
|
| 1211 |
+
本项目采用 **MIT License** 发布。你可以根据 MIT License 的条款使用、复制、修改、分发本项目源代码,但必须保留原始版权声明与许可证文本。
|
| 1212 |
+
|
| 1213 |
+
### 使用范围说明
|
| 1214 |
+
|
| 1215 |
+
本项目用于协议兼容、接口转换、自动化测试与个人技术研究。项目本身不提供任何官方授权的通义千问商业接口服务。
|
| 1216 |
+
|
| 1217 |
+
### 免责声明
|
| 1218 |
+
|
| 1219 |
+
1. 本项目与阿里云、通义千问及相关官方服务无任何从属、代理或商业合作关系。
|
| 1220 |
+
2. 本项目不是官方产品,也不构成任何官方服务承诺。
|
| 1221 |
+
3. 使用者应自行评估所在地区的法律法规、上游服务条款、账号合规性与数据安全要求。
|
| 1222 |
+
4. 因使用本项目导致的账号封禁、请求受限、数据丢失、服务中断、法律纠纷或其他风险,由使用者自行承担责任。
|
| 1223 |
+
5. 项目维护者不对任何直接或间接损失承担责任。
|
| 1224 |
+
6. 不建议将本项目用于违反上游服务条款、违反法律法规或存在明显合规风险的场景。
|
| 1225 |
+
|
| 1226 |
+
如果权利人认为本项目内容侵犯其合法权益,请通过仓库 Issue 或其他公开联系方式提出,维护者将在核实后处理。
|
backend/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Backend package
|
backend/accounts.json
ADDED
|
@@ -0,0 +1,13 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
[
|
| 2 |
+
{
|
| 3 |
+
"email": "test@test.com",
|
| 4 |
+
"token": "fake_token",
|
| 5 |
+
"password": "test",
|
| 6 |
+
"is_valid": true,
|
| 7 |
+
"last_used": 0,
|
| 8 |
+
"inflight": 0,
|
| 9 |
+
"activation_pending": false,
|
| 10 |
+
"created_at": 1712534400,
|
| 11 |
+
"rate_limited_until": 0
|
| 12 |
+
}
|
| 13 |
+
]
|
backend/adapter/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
from .standard_request import StandardRequest
|
backend/adapter/cli_proxy.py
ADDED
|
@@ -0,0 +1,258 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
"""
|
| 2 |
+
CLIProxy - 协议转换代理层
|
| 3 |
+
统一处理 OpenAI/Claude/Gemini 协议到 StandardRequest 的转换
|
| 4 |
+
"""
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from backend.adapter.standard_request import StandardRequest, CLAUDE_CODE_OPENAI_PROFILE
|
| 9 |
+
from backend.core.config import resolve_model
|
| 10 |
+
from backend.services.prompt_builder import messages_to_prompt
|
| 11 |
+
from backend.toolcall.normalize import build_tool_name_registry
|
| 12 |
+
|
| 13 |
+
log = logging.getLogger("qwen2api.cli_proxy")
|
| 14 |
+
|
| 15 |
+
|
| 16 |
+
class CLIProxy:
|
| 17 |
+
"""
|
| 18 |
+
协议转换代理 - 类似 ds2api 的 CLIProxy
|
| 19 |
+
负责将不同协议(OpenAI/Claude/Gemini)转换为统一的 StandardRequest
|
| 20 |
+
"""
|
| 21 |
+
|
| 22 |
+
@staticmethod
|
| 23 |
+
def from_openai(req_data: dict, *, client_profile: str = CLAUDE_CODE_OPENAI_PROFILE) -> StandardRequest:
|
| 24 |
+
"""
|
| 25 |
+
OpenAI 协议 -> StandardRequest
|
| 26 |
+
|
| 27 |
+
Args:
|
| 28 |
+
req_data: OpenAI 格式的请求体
|
| 29 |
+
client_profile: 客户端配置文件
|
| 30 |
+
|
| 31 |
+
Returns:
|
| 32 |
+
StandardRequest: 统一的标准请求对象
|
| 33 |
+
"""
|
| 34 |
+
model_name = req_data.get("model", "gpt-4o")
|
| 35 |
+
prompt_result = messages_to_prompt(req_data, client_profile=client_profile)
|
| 36 |
+
|
| 37 |
+
tools = prompt_result.tools
|
| 38 |
+
tool_names = [
|
| 39 |
+
tool_name
|
| 40 |
+
for tool_name in (tool.get("name") for tool in tools)
|
| 41 |
+
if isinstance(tool_name, str) and tool_name
|
| 42 |
+
]
|
| 43 |
+
|
| 44 |
+
return StandardRequest(
|
| 45 |
+
prompt=prompt_result.prompt,
|
| 46 |
+
response_model=model_name,
|
| 47 |
+
resolved_model=resolve_model(model_name),
|
| 48 |
+
surface="openai",
|
| 49 |
+
client_profile=client_profile,
|
| 50 |
+
requested_model=model_name,
|
| 51 |
+
stream=req_data.get("stream", False),
|
| 52 |
+
tools=tools,
|
| 53 |
+
tool_names=tool_names,
|
| 54 |
+
tool_name_registry=build_tool_name_registry(tool_names),
|
| 55 |
+
tool_enabled=prompt_result.tool_enabled,
|
| 56 |
+
)
|
| 57 |
+
|
| 58 |
+
@staticmethod
|
| 59 |
+
def from_anthropic(req_data: dict, *, client_profile: str = CLAUDE_CODE_OPENAI_PROFILE) -> StandardRequest:
|
| 60 |
+
"""
|
| 61 |
+
Anthropic Claude 协议 -> StandardRequest
|
| 62 |
+
|
| 63 |
+
Args:
|
| 64 |
+
req_data: Claude 格式的请求体
|
| 65 |
+
client_profile: 客户端配置文件
|
| 66 |
+
|
| 67 |
+
Returns:
|
| 68 |
+
StandardRequest: 统一的标准请求对象
|
| 69 |
+
"""
|
| 70 |
+
model_name = req_data.get("model", "claude-3-5-sonnet")
|
| 71 |
+
prompt_result = messages_to_prompt(req_data, client_profile=client_profile)
|
| 72 |
+
|
| 73 |
+
tools = prompt_result.tools
|
| 74 |
+
tool_names = [
|
| 75 |
+
tool_name
|
| 76 |
+
for tool_name in (tool.get("name") for tool in tools)
|
| 77 |
+
if isinstance(tool_name, str) and tool_name
|
| 78 |
+
]
|
| 79 |
+
|
| 80 |
+
return StandardRequest(
|
| 81 |
+
prompt=prompt_result.prompt,
|
| 82 |
+
response_model=model_name,
|
| 83 |
+
resolved_model=resolve_model(model_name),
|
| 84 |
+
surface="anthropic",
|
| 85 |
+
client_profile=client_profile,
|
| 86 |
+
requested_model=model_name,
|
| 87 |
+
stream=req_data.get("stream", False),
|
| 88 |
+
tools=tools,
|
| 89 |
+
tool_names=tool_names,
|
| 90 |
+
tool_name_registry=build_tool_name_registry(tool_names),
|
| 91 |
+
tool_enabled=prompt_result.tool_enabled,
|
| 92 |
+
)
|
| 93 |
+
|
| 94 |
+
@staticmethod
|
| 95 |
+
def from_gemini(model: str, req_data: dict, *, stream: bool | None = None) -> StandardRequest:
|
| 96 |
+
"""
|
| 97 |
+
Google Gemini 协议 -> StandardRequest
|
| 98 |
+
|
| 99 |
+
Args:
|
| 100 |
+
model: Gemini 模型名称
|
| 101 |
+
req_data: Gemini 格式的请求体
|
| 102 |
+
stream: 是否流式输出(None 则从请求体推断)
|
| 103 |
+
|
| 104 |
+
Returns:
|
| 105 |
+
StandardRequest: 统一的标准请求对象
|
| 106 |
+
"""
|
| 107 |
+
prompt = CLIProxy._extract_gemini_prompt(req_data)
|
| 108 |
+
stream_requested = CLIProxy._is_gemini_stream_request(req_data) if stream is None else stream
|
| 109 |
+
|
| 110 |
+
# Gemini 暂不支持工具调用,后续可扩展
|
| 111 |
+
tools = []
|
| 112 |
+
tool_names = []
|
| 113 |
+
|
| 114 |
+
return StandardRequest(
|
| 115 |
+
prompt=prompt,
|
| 116 |
+
response_model=model,
|
| 117 |
+
resolved_model=resolve_model(model),
|
| 118 |
+
surface="gemini",
|
| 119 |
+
requested_model=model,
|
| 120 |
+
content=prompt,
|
| 121 |
+
stream=stream_requested,
|
| 122 |
+
tools=tools,
|
| 123 |
+
tool_names=tool_names,
|
| 124 |
+
tool_name_registry={},
|
| 125 |
+
tool_enabled=False,
|
| 126 |
+
)
|
| 127 |
+
|
| 128 |
+
@staticmethod
|
| 129 |
+
def _extract_gemini_prompt(body: dict) -> str:
|
| 130 |
+
"""从 Gemini 请求体中提取 prompt"""
|
| 131 |
+
lines: list[str] = []
|
| 132 |
+
for message in body.get("contents", []) or []:
|
| 133 |
+
if message.get("role") != "user":
|
| 134 |
+
continue
|
| 135 |
+
for part in message.get("parts", []) or []:
|
| 136 |
+
text = part.get("text")
|
| 137 |
+
if text:
|
| 138 |
+
lines.append(text)
|
| 139 |
+
return "\n".join(lines)
|
| 140 |
+
|
| 141 |
+
@staticmethod
|
| 142 |
+
def _is_gemini_stream_request(body: dict[str, Any]) -> bool:
|
| 143 |
+
"""判断 Gemini 请求是否为流式"""
|
| 144 |
+
if body.get("stream") is True:
|
| 145 |
+
return True
|
| 146 |
+
generation_config = body.get("generationConfig")
|
| 147 |
+
if isinstance(generation_config, dict) and generation_config.get("stream") is True:
|
| 148 |
+
return True
|
| 149 |
+
return False
|
| 150 |
+
|
| 151 |
+
@staticmethod
|
| 152 |
+
def to_openai_response(execution, standard_request: StandardRequest) -> dict:
|
| 153 |
+
"""
|
| 154 |
+
StandardRequest 执行结果 -> OpenAI 响应格式
|
| 155 |
+
|
| 156 |
+
Args:
|
| 157 |
+
execution: 执行结果对象
|
| 158 |
+
standard_request: 原始标准请求
|
| 159 |
+
|
| 160 |
+
Returns:
|
| 161 |
+
dict: OpenAI 格式的响应
|
| 162 |
+
"""
|
| 163 |
+
return {
|
| 164 |
+
"id": f"chatcmpl-{execution.chat_id[:12]}",
|
| 165 |
+
"object": "chat.completion",
|
| 166 |
+
"created": int(execution.state.created_at or 0),
|
| 167 |
+
"model": standard_request.response_model,
|
| 168 |
+
"choices": [
|
| 169 |
+
{
|
| 170 |
+
"index": 0,
|
| 171 |
+
"message": {
|
| 172 |
+
"role": "assistant",
|
| 173 |
+
"content": execution.state.answer_text,
|
| 174 |
+
},
|
| 175 |
+
"finish_reason": "stop",
|
| 176 |
+
}
|
| 177 |
+
],
|
| 178 |
+
"usage": {
|
| 179 |
+
"prompt_tokens": len(standard_request.prompt),
|
| 180 |
+
"completion_tokens": len(execution.state.answer_text),
|
| 181 |
+
"total_tokens": len(standard_request.prompt) + len(execution.state.answer_text),
|
| 182 |
+
},
|
| 183 |
+
}
|
| 184 |
+
|
| 185 |
+
@staticmethod
|
| 186 |
+
def to_anthropic_response(execution, standard_request: StandardRequest, msg_id: str, directive) -> dict:
|
| 187 |
+
"""
|
| 188 |
+
StandardRequest 执行结果 -> Anthropic Claude 响应格式
|
| 189 |
+
|
| 190 |
+
Args:
|
| 191 |
+
execution: 执行结果对象
|
| 192 |
+
standard_request: 原始标准请求
|
| 193 |
+
msg_id: 消息 ID
|
| 194 |
+
directive: 工具调用指令
|
| 195 |
+
|
| 196 |
+
Returns:
|
| 197 |
+
dict: Claude 格式的响应
|
| 198 |
+
"""
|
| 199 |
+
content_blocks: list[dict] = []
|
| 200 |
+
|
| 201 |
+
# 添加思考内容
|
| 202 |
+
if execution.state.reasoning_text:
|
| 203 |
+
content_blocks.append({"type": "thinking", "thinking": execution.state.reasoning_text})
|
| 204 |
+
|
| 205 |
+
# 添加工具调用块
|
| 206 |
+
content_blocks.extend(directive.tool_blocks)
|
| 207 |
+
|
| 208 |
+
return {
|
| 209 |
+
"id": msg_id,
|
| 210 |
+
"type": "message",
|
| 211 |
+
"role": "assistant",
|
| 212 |
+
"model": standard_request.response_model,
|
| 213 |
+
"content": content_blocks,
|
| 214 |
+
"stop_reason": directive.stop_reason,
|
| 215 |
+
"stop_sequence": None,
|
| 216 |
+
"usage": {
|
| 217 |
+
"input_tokens": len(standard_request.prompt),
|
| 218 |
+
"output_tokens": len(execution.state.answer_text),
|
| 219 |
+
},
|
| 220 |
+
}
|
| 221 |
+
|
| 222 |
+
@staticmethod
|
| 223 |
+
def to_gemini_response(execution, standard_request: StandardRequest) -> dict:
|
| 224 |
+
"""
|
| 225 |
+
StandardRequest 执行结果 -> Google Gemini 响应格式
|
| 226 |
+
|
| 227 |
+
Args:
|
| 228 |
+
execution: 执行结果对象
|
| 229 |
+
standard_request: 原始标准请求
|
| 230 |
+
|
| 231 |
+
Returns:
|
| 232 |
+
dict: Gemini 格式的响应
|
| 233 |
+
"""
|
| 234 |
+
return {
|
| 235 |
+
"candidates": [
|
| 236 |
+
{
|
| 237 |
+
"content": {
|
| 238 |
+
"parts": [{"text": execution.state.answer_text}],
|
| 239 |
+
"role": "model",
|
| 240 |
+
},
|
| 241 |
+
"finishReason": "STOP",
|
| 242 |
+
"index": 0,
|
| 243 |
+
}
|
| 244 |
+
],
|
| 245 |
+
"usageMetadata": {
|
| 246 |
+
"promptTokenCount": len(standard_request.prompt),
|
| 247 |
+
"candidatesTokenCount": len(execution.state.answer_text),
|
| 248 |
+
"totalTokenCount": len(standard_request.prompt) + len(execution.state.answer_text),
|
| 249 |
+
},
|
| 250 |
+
}
|
| 251 |
+
|
| 252 |
+
@staticmethod
|
| 253 |
+
def log_conversion(surface: str, model: str, prompt_len: int, tool_count: int):
|
| 254 |
+
"""记录协议转换日志"""
|
| 255 |
+
log.info(
|
| 256 |
+
f"[CLIProxy] {surface.upper()} -> StandardRequest: "
|
| 257 |
+
f"model={model}, prompt_len={prompt_len}, tools={tool_count}"
|
| 258 |
+
)
|
backend/adapter/standard_request.py
ADDED
|
@@ -0,0 +1,38 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from backend.runtime.attachment_types import NormalizedAttachment
|
| 7 |
+
|
| 8 |
+
CLAUDE_CODE_OPENAI_PROFILE = "claude_code_openai"
|
| 9 |
+
OPENCLAW_OPENAI_PROFILE = "openclaw_openai"
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
@dataclass(slots=True)
|
| 13 |
+
class StandardRequest:
|
| 14 |
+
prompt: str
|
| 15 |
+
response_model: str
|
| 16 |
+
resolved_model: str
|
| 17 |
+
surface: str
|
| 18 |
+
client_profile: str = OPENCLAW_OPENAI_PROFILE
|
| 19 |
+
requested_model: str | None = None
|
| 20 |
+
content: str | None = None
|
| 21 |
+
stream: bool = False
|
| 22 |
+
tools: list[dict[str, Any]] = field(default_factory=list)
|
| 23 |
+
tool_names: list[str] = field(default_factory=list)
|
| 24 |
+
tool_name_registry: dict[str, str] = field(default_factory=dict)
|
| 25 |
+
tool_enabled: bool = False
|
| 26 |
+
attachments: list[NormalizedAttachment] = field(default_factory=list)
|
| 27 |
+
uploaded_file_ids: list[str] = field(default_factory=list)
|
| 28 |
+
upstream_files: list[dict[str, Any]] = field(default_factory=list)
|
| 29 |
+
session_key: str | None = None
|
| 30 |
+
context_mode: str = "inline"
|
| 31 |
+
bound_account_email: str | None = None
|
| 32 |
+
bound_account: Any | None = None
|
| 33 |
+
stage_labels: dict[str, str] = field(default_factory=dict)
|
| 34 |
+
full_prompt: str | None = None
|
| 35 |
+
upstream_chat_id: str | None = None
|
| 36 |
+
persistent_session: bool = False
|
| 37 |
+
session_message_hashes: list[str] = field(default_factory=list)
|
| 38 |
+
session_chat_invalidated: bool = False
|
backend/api/__init__.py
ADDED
|
File without changes
|
backend/api/admin.py
ADDED
|
@@ -0,0 +1,342 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Depends, HTTPException, Header, Request
|
| 2 |
+
from pydantic import BaseModel
|
| 3 |
+
from backend.core.config import settings
|
| 4 |
+
from backend.core.database import AsyncJsonDB
|
| 5 |
+
from backend.core.account_pool import AccountPool, Account
|
| 6 |
+
import secrets
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
def verify_admin(authorization: str = Header(None)):
|
| 11 |
+
if not authorization or not authorization.startswith("Bearer "):
|
| 12 |
+
raise HTTPException(status_code=401, detail="Unauthorized")
|
| 13 |
+
token = authorization.split("Bearer ")[1]
|
| 14 |
+
|
| 15 |
+
from backend.core.config import API_KEYS, settings as backend_settings
|
| 16 |
+
|
| 17 |
+
# 允许使用默认管理员 Key (ADMIN_KEY) 或者任何已生成的 API_KEYS 作为管理凭证
|
| 18 |
+
if token != backend_settings.ADMIN_KEY and token not in API_KEYS:
|
| 19 |
+
raise HTTPException(status_code=403, detail="Forbidden: Admin Key Mismatch")
|
| 20 |
+
return token
|
| 21 |
+
|
| 22 |
+
class UserCreate(BaseModel):
|
| 23 |
+
name: str
|
| 24 |
+
quota: int = 1000000
|
| 25 |
+
|
| 26 |
+
class User(BaseModel):
|
| 27 |
+
id: str
|
| 28 |
+
name: str
|
| 29 |
+
quota: int
|
| 30 |
+
used_tokens: int
|
| 31 |
+
|
| 32 |
+
@router.get("/status", dependencies=[Depends(verify_admin)])
|
| 33 |
+
async def get_system_status(request: Request):
|
| 34 |
+
pool = request.app.state.account_pool
|
| 35 |
+
|
| 36 |
+
# 账号层细粒度 inflight / 状态
|
| 37 |
+
per_account = []
|
| 38 |
+
for acc in getattr(pool, "accounts", []):
|
| 39 |
+
per_account.append({
|
| 40 |
+
"email": acc.email,
|
| 41 |
+
"status": acc.get_status_code(),
|
| 42 |
+
"inflight": getattr(acc, "inflight", 0),
|
| 43 |
+
"max_inflight": getattr(pool, "max_inflight_per_account", 0),
|
| 44 |
+
"consecutive_failures": getattr(acc, "consecutive_failures", 0),
|
| 45 |
+
"rate_limit_strikes": getattr(acc, "rate_limit_strikes", 0),
|
| 46 |
+
"last_request_finished": getattr(acc, "last_request_finished", 0),
|
| 47 |
+
})
|
| 48 |
+
|
| 49 |
+
# chat_id 预热池指标(若已启用)
|
| 50 |
+
chat_id_pool_stats = None
|
| 51 |
+
cp = getattr(request.app.state, "chat_id_pool", None)
|
| 52 |
+
if cp is not None:
|
| 53 |
+
try:
|
| 54 |
+
per_account_pool: dict[str, int] = {}
|
| 55 |
+
for acc in getattr(pool, "accounts", []):
|
| 56 |
+
per_account_pool[acc.email] = await cp.size(acc.email)
|
| 57 |
+
chat_id_pool_stats = {
|
| 58 |
+
"total_cached": await cp.total_size(),
|
| 59 |
+
"target_per_account": cp._target,
|
| 60 |
+
"ttl_seconds": cp._ttl,
|
| 61 |
+
"per_account": per_account_pool,
|
| 62 |
+
}
|
| 63 |
+
except Exception:
|
| 64 |
+
chat_id_pool_stats = {"error": "snapshot failed"}
|
| 65 |
+
|
| 66 |
+
# 向运行时拿全局任务计数 / asyncio 状态
|
| 67 |
+
import asyncio
|
| 68 |
+
try:
|
| 69 |
+
tasks = asyncio.all_tasks()
|
| 70 |
+
running_tasks = sum(1 for t in tasks if not t.done())
|
| 71 |
+
except Exception:
|
| 72 |
+
running_tasks = -1
|
| 73 |
+
|
| 74 |
+
return {
|
| 75 |
+
"accounts": pool.status(),
|
| 76 |
+
"per_account": per_account,
|
| 77 |
+
"chat_id_pool": chat_id_pool_stats,
|
| 78 |
+
"runtime": {
|
| 79 |
+
"asyncio_running_tasks": running_tasks,
|
| 80 |
+
},
|
| 81 |
+
"request_runtime": {
|
| 82 |
+
"mode": "direct_http",
|
| 83 |
+
"browser_required_for_requests": False,
|
| 84 |
+
"description": "普通请求直连 HTTP,不经过浏览器",
|
| 85 |
+
},
|
| 86 |
+
"browser_automation": {
|
| 87 |
+
"mode": "on_demand_registration_only",
|
| 88 |
+
"description": "仅注册/激活/刷新 Token 时按需启动真实浏览器",
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
|
| 92 |
+
@router.get("/users", dependencies=[Depends(verify_admin)])
|
| 93 |
+
async def list_users(request: Request):
|
| 94 |
+
db: AsyncJsonDB = request.app.state.users_db
|
| 95 |
+
data = await db.get()
|
| 96 |
+
return {"users": data}
|
| 97 |
+
|
| 98 |
+
@router.post("/users", dependencies=[Depends(verify_admin)])
|
| 99 |
+
async def create_user(user: UserCreate, request: Request):
|
| 100 |
+
import uuid
|
| 101 |
+
db: AsyncJsonDB = request.app.state.users_db
|
| 102 |
+
data = await db.get()
|
| 103 |
+
new_user = {
|
| 104 |
+
"id": f"sk-{uuid.uuid4().hex}",
|
| 105 |
+
"name": user.name,
|
| 106 |
+
"quota": user.quota,
|
| 107 |
+
"used_tokens": 0
|
| 108 |
+
}
|
| 109 |
+
data.append(new_user)
|
| 110 |
+
await db.save(data)
|
| 111 |
+
return new_user
|
| 112 |
+
|
| 113 |
+
@router.post("/accounts", dependencies=[Depends(verify_admin)])
|
| 114 |
+
async def add_account(request: Request):
|
| 115 |
+
import time
|
| 116 |
+
from backend.core.account_pool import Account, AccountPool
|
| 117 |
+
from backend.services.qwen_client import QwenClient
|
| 118 |
+
|
| 119 |
+
pool: AccountPool = request.app.state.account_pool
|
| 120 |
+
client: QwenClient = request.app.state.qwen_client
|
| 121 |
+
|
| 122 |
+
try:
|
| 123 |
+
data = await request.json()
|
| 124 |
+
except Exception:
|
| 125 |
+
raise HTTPException(400, detail="Invalid JSON body")
|
| 126 |
+
|
| 127 |
+
token = data.get("token", "")
|
| 128 |
+
if not token:
|
| 129 |
+
raise HTTPException(400, detail="token is required")
|
| 130 |
+
|
| 131 |
+
acc = Account(
|
| 132 |
+
email=data.get("email", f"manual_{int(time.time())}@qwen"),
|
| 133 |
+
password=data.get("password", ""),
|
| 134 |
+
token=token,
|
| 135 |
+
cookies=data.get("cookies", ""),
|
| 136 |
+
username=data.get("username", "")
|
| 137 |
+
)
|
| 138 |
+
|
| 139 |
+
is_valid = await client.verify_token(token)
|
| 140 |
+
if not is_valid:
|
| 141 |
+
return {"ok": False, "error": "Invalid token (验证失败,请确认Token有效)"}
|
| 142 |
+
|
| 143 |
+
await pool.add(acc)
|
| 144 |
+
return {"ok": True, "email": acc.email}
|
| 145 |
+
|
| 146 |
+
|
| 147 |
+
@router.get("/accounts", dependencies=[Depends(verify_admin)])
|
| 148 |
+
async def list_accounts(request: Request):
|
| 149 |
+
pool: AccountPool = request.app.state.account_pool
|
| 150 |
+
# 模拟原始 FastAPI 序列化,包含运行时状态
|
| 151 |
+
accs = []
|
| 152 |
+
for a in pool.accounts:
|
| 153 |
+
d = a.to_dict()
|
| 154 |
+
d["valid"] = a.valid
|
| 155 |
+
d["inflight"] = a.inflight
|
| 156 |
+
d["rate_limited_until"] = a.rate_limited_until
|
| 157 |
+
accs.append(d)
|
| 158 |
+
return {"accounts": accs}
|
| 159 |
+
|
| 160 |
+
@router.post("/accounts/register", dependencies=[Depends(verify_admin)])
|
| 161 |
+
async def register_new_account(request: Request):
|
| 162 |
+
"""一键调用浏览器无头注册新千问账号"""
|
| 163 |
+
import logging
|
| 164 |
+
from backend.services.auth_resolver import register_qwen_account
|
| 165 |
+
from backend.core.account_pool import AccountPool
|
| 166 |
+
pool: AccountPool = request.app.state.account_pool
|
| 167 |
+
|
| 168 |
+
log = logging.getLogger("backend.api.admin")
|
| 169 |
+
|
| 170 |
+
client_ip = request.client.host if request.client else "127.0.0.1"
|
| 171 |
+
log.info(f"[注册] 管理员触发注册,来源IP: {client_ip}")
|
| 172 |
+
|
| 173 |
+
# 简单的频率限制保护
|
| 174 |
+
current = len(pool.accounts)
|
| 175 |
+
if current >= 100:
|
| 176 |
+
return {"ok": False, "error": "账号池已满,请先清理死号"}
|
| 177 |
+
|
| 178 |
+
try:
|
| 179 |
+
acc = await register_qwen_account()
|
| 180 |
+
if acc:
|
| 181 |
+
await pool.add(acc)
|
| 182 |
+
log.info(f"[注册] 注册成功: {acc.email}(当前账号数: {len(pool.accounts)}/100)")
|
| 183 |
+
return {"ok": True, "email": acc.email, "message": "新账号注册成功并已入池"}
|
| 184 |
+
return {"ok": False, "error": "自动化注册失败,可能遇到风控或页面元素改变"}
|
| 185 |
+
except Exception as e:
|
| 186 |
+
return {"ok": False, "error": f"注册发生异常: {str(e)}"}
|
| 187 |
+
|
| 188 |
+
@router.post("/verify", dependencies=[Depends(verify_admin)])
|
| 189 |
+
async def verify_all_accounts(request: Request):
|
| 190 |
+
"""验证所有账号的有效性 (完全复原单文件逻辑)"""
|
| 191 |
+
from backend.core.account_pool import AccountPool
|
| 192 |
+
from backend.services.qwen_client import QwenClient
|
| 193 |
+
import logging
|
| 194 |
+
|
| 195 |
+
log = logging.getLogger("qwen2api.admin")
|
| 196 |
+
pool: AccountPool = request.app.state.account_pool
|
| 197 |
+
client: QwenClient = request.app.state.qwen_client
|
| 198 |
+
|
| 199 |
+
results = []
|
| 200 |
+
for acc in pool.accounts:
|
| 201 |
+
is_valid = await client.verify_token(acc.token)
|
| 202 |
+
if not is_valid and acc.password:
|
| 203 |
+
log.info(f"[校验] {acc.email} token失效,尝试自动刷新...")
|
| 204 |
+
is_valid = await client.auth_resolver.refresh_token(acc)
|
| 205 |
+
|
| 206 |
+
acc.valid = is_valid
|
| 207 |
+
results.append({"email": acc.email, "valid": is_valid, "refreshed": not is_valid})
|
| 208 |
+
|
| 209 |
+
await pool.save() # 直接保存全部状态,不调用 mark_invalid 以免熔断影响测试
|
| 210 |
+
return {"ok": True, "results": results}
|
| 211 |
+
|
| 212 |
+
@router.post("/accounts/{email}/activate", dependencies=[Depends(verify_admin)])
|
| 213 |
+
async def activate_account(email: str, request: Request):
|
| 214 |
+
"""单独激活某个账号"""
|
| 215 |
+
from backend.services.auth_resolver import activate_account as activate_logic
|
| 216 |
+
from backend.core.account_pool import AccountPool
|
| 217 |
+
|
| 218 |
+
pool: AccountPool = request.app.state.account_pool
|
| 219 |
+
acc = next((a for a in pool.accounts if a.email == email), None)
|
| 220 |
+
if not acc:
|
| 221 |
+
raise HTTPException(status_code=404, detail="Account not found")
|
| 222 |
+
|
| 223 |
+
# 防止并发点击:检查一个运行时标志
|
| 224 |
+
if getattr(acc, "_is_activating", False):
|
| 225 |
+
return {"ok": False, "error": "该账号正在激活中,请勿重复点击"}
|
| 226 |
+
|
| 227 |
+
try:
|
| 228 |
+
setattr(acc, "_is_activating", True)
|
| 229 |
+
success = await activate_logic(acc)
|
| 230 |
+
if success:
|
| 231 |
+
acc.valid = True
|
| 232 |
+
acc.activation_pending = False
|
| 233 |
+
await pool.add(acc) # 这会触发覆盖保存
|
| 234 |
+
return {"ok": True, "message": "账号激活成功"}
|
| 235 |
+
return {"ok": False, "error": "未能找到激活链接或获取Token"}
|
| 236 |
+
finally:
|
| 237 |
+
setattr(acc, "_is_activating", False)
|
| 238 |
+
|
| 239 |
+
@router.post("/accounts/{email}/verify", dependencies=[Depends(verify_admin)])
|
| 240 |
+
async def verify_account(email: str, request: Request):
|
| 241 |
+
"""单独验证某个账号的有效性 (完全复原单文件逻辑)"""
|
| 242 |
+
from backend.services.qwen_client import QwenClient
|
| 243 |
+
from backend.core.account_pool import AccountPool
|
| 244 |
+
import logging
|
| 245 |
+
|
| 246 |
+
log = logging.getLogger("qwen2api.admin")
|
| 247 |
+
pool: AccountPool = request.app.state.account_pool
|
| 248 |
+
client: QwenClient = request.app.state.qwen_client
|
| 249 |
+
|
| 250 |
+
acc = next((a for a in pool.accounts if a.email == email), None)
|
| 251 |
+
if not acc:
|
| 252 |
+
raise HTTPException(status_code=404, detail="Account not found")
|
| 253 |
+
|
| 254 |
+
is_valid = await client.verify_token(acc.token)
|
| 255 |
+
if not is_valid and acc.password:
|
| 256 |
+
log.info(f"[校验] {acc.email} token失效,尝试自动��新...")
|
| 257 |
+
is_valid = await client.auth_resolver.refresh_token(acc)
|
| 258 |
+
|
| 259 |
+
acc.valid = is_valid
|
| 260 |
+
await pool.save() # 直接保存,不调用 mark_invalid 以免熔断影响正常测试
|
| 261 |
+
|
| 262 |
+
return {"email": acc.email, "valid": is_valid}
|
| 263 |
+
|
| 264 |
+
@router.delete("/accounts/{email}", dependencies=[Depends(verify_admin)])
|
| 265 |
+
async def delete_account(email: str, request: Request):
|
| 266 |
+
from backend.core.account_pool import AccountPool
|
| 267 |
+
pool: AccountPool = request.app.state.account_pool
|
| 268 |
+
await pool.remove(email)
|
| 269 |
+
return {"ok": True}
|
| 270 |
+
|
| 271 |
+
@router.get("/settings", dependencies=[Depends(verify_admin)])
|
| 272 |
+
async def get_settings(request: Request):
|
| 273 |
+
from backend.core.config import MODEL_MAP
|
| 274 |
+
from backend.core.config import settings as backend_settings
|
| 275 |
+
|
| 276 |
+
safe_map = {k: v for k, v in MODEL_MAP.items()}
|
| 277 |
+
pool = getattr(request.app.state, "chat_id_pool", None)
|
| 278 |
+
acc_pool = getattr(request.app.state, "account_pool", None)
|
| 279 |
+
return {
|
| 280 |
+
"version": "2.0.0",
|
| 281 |
+
"max_inflight_per_account": backend_settings.MAX_INFLIGHT_PER_ACCOUNT,
|
| 282 |
+
"global_max_inflight": getattr(acc_pool, "global_max_inflight", 0),
|
| 283 |
+
"max_queue_size": getattr(acc_pool, "max_queue_size", 0),
|
| 284 |
+
"chat_id_pool_target": pool.target if pool else 0,
|
| 285 |
+
"chat_id_pool_ttl_seconds": pool.ttl if pool else 0,
|
| 286 |
+
"model_aliases": safe_map,
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
@router.put("/settings", dependencies=[Depends(verify_admin)])
|
| 290 |
+
async def update_settings(data: dict, request: Request):
|
| 291 |
+
from backend.core.config import MODEL_MAP
|
| 292 |
+
if "max_inflight_per_account" in data:
|
| 293 |
+
try:
|
| 294 |
+
val = int(data["max_inflight_per_account"])
|
| 295 |
+
settings.MAX_INFLIGHT_PER_ACCOUNT = val
|
| 296 |
+
pool = getattr(request.app.state, "account_pool", None)
|
| 297 |
+
if pool is not None and hasattr(pool, "set_max_inflight"):
|
| 298 |
+
pool.set_max_inflight(val)
|
| 299 |
+
except (TypeError, ValueError):
|
| 300 |
+
pass
|
| 301 |
+
if "global_max_inflight" in data:
|
| 302 |
+
try:
|
| 303 |
+
val = int(data["global_max_inflight"])
|
| 304 |
+
pool = getattr(request.app.state, "account_pool", None)
|
| 305 |
+
if pool is not None and val > 0:
|
| 306 |
+
pool.global_max_inflight = val
|
| 307 |
+
except (TypeError, ValueError):
|
| 308 |
+
pass
|
| 309 |
+
if "chat_id_pool_target" in data or "chat_id_pool_ttl_seconds" in data:
|
| 310 |
+
cp = getattr(request.app.state, "chat_id_pool", None)
|
| 311 |
+
if cp is not None:
|
| 312 |
+
cp.update_config(
|
| 313 |
+
target=data.get("chat_id_pool_target"),
|
| 314 |
+
ttl_seconds=data.get("chat_id_pool_ttl_seconds"),
|
| 315 |
+
)
|
| 316 |
+
if "model_aliases" in data:
|
| 317 |
+
MODEL_MAP.clear()
|
| 318 |
+
MODEL_MAP.update(data["model_aliases"])
|
| 319 |
+
return {"ok": True}
|
| 320 |
+
|
| 321 |
+
@router.get("/keys", dependencies=[Depends(verify_admin)])
|
| 322 |
+
async def get_keys():
|
| 323 |
+
from backend.core.config import API_KEYS
|
| 324 |
+
return {"keys": list(API_KEYS)}
|
| 325 |
+
|
| 326 |
+
@router.post("/keys", dependencies=[Depends(verify_admin)])
|
| 327 |
+
async def create_key():
|
| 328 |
+
from backend.core.config import API_KEYS, save_api_keys
|
| 329 |
+
|
| 330 |
+
new_key = f"sk-{secrets.token_hex(24)}"
|
| 331 |
+
API_KEYS.add(new_key)
|
| 332 |
+
save_api_keys(API_KEYS)
|
| 333 |
+
return {"ok": True, "key": new_key}
|
| 334 |
+
|
| 335 |
+
@router.delete("/keys/{key}", dependencies=[Depends(verify_admin)])
|
| 336 |
+
async def delete_key(key: str):
|
| 337 |
+
from backend.core.config import API_KEYS, save_api_keys
|
| 338 |
+
|
| 339 |
+
if key in API_KEYS:
|
| 340 |
+
API_KEYS.remove(key)
|
| 341 |
+
save_api_keys(API_KEYS)
|
| 342 |
+
return {"ok": True}
|
backend/api/anthropic.py
ADDED
|
@@ -0,0 +1,513 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 2 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 3 |
+
import asyncio
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import uuid
|
| 7 |
+
|
| 8 |
+
from backend.adapter.standard_request import StandardRequest
|
| 9 |
+
from backend.adapter.cli_proxy import CLIProxy
|
| 10 |
+
from backend.core.config import resolve_model, settings
|
| 11 |
+
from backend.core.request_logging import new_request_id, request_context, update_request_context
|
| 12 |
+
from backend.runtime import stream_presenter
|
| 13 |
+
from backend.runtime.execution import (
|
| 14 |
+
build_tool_directive,
|
| 15 |
+
cleanup_runtime_resources,
|
| 16 |
+
collect_completion_run,
|
| 17 |
+
collect_completion_run_with_recovery,
|
| 18 |
+
evaluate_retry_directive,
|
| 19 |
+
request_max_attempts,
|
| 20 |
+
)
|
| 21 |
+
from backend.services.auth_quota import resolve_auth_context
|
| 22 |
+
from backend.services.context_attachment_manager import prepare_context_attachments, derive_session_key
|
| 23 |
+
from backend.services.attachment_preprocessor import preprocess_attachments
|
| 24 |
+
from backend.services.prompt_builder import CLAUDE_CODE_OPENAI_PROFILE, messages_to_prompt
|
| 25 |
+
from backend.services.qwen_client import QwenClient
|
| 26 |
+
from backend.services.task_session import (
|
| 27 |
+
build_anthropic_assistant_history_message,
|
| 28 |
+
build_retry_rebase_prompt,
|
| 29 |
+
clear_invalidated_session_chat,
|
| 30 |
+
log_session_plan_reuse_cancelled,
|
| 31 |
+
persist_session_turn,
|
| 32 |
+
plan_persistent_session_turn,
|
| 33 |
+
)
|
| 34 |
+
from backend.services.token_calc import count_tokens
|
| 35 |
+
from backend.toolcall.normalize import build_tool_name_registry
|
| 36 |
+
|
| 37 |
+
log = logging.getLogger("qwen2api.anthropic")
|
| 38 |
+
router = APIRouter()
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
class _AnthropicStreamState:
|
| 42 |
+
def __init__(self, *, msg_id: str, model_name: str, prompt: str):
|
| 43 |
+
self.msg_id = msg_id
|
| 44 |
+
self.model_name = model_name
|
| 45 |
+
self.prompt = prompt
|
| 46 |
+
self.pending_chunks: list[str] = []
|
| 47 |
+
self.answer_text_buffer: list[tuple[int, str]] = []
|
| 48 |
+
self.block_index = 0
|
| 49 |
+
self.current_block: dict[str, object] = {"type": None, "index": None, "tool_call_id": None}
|
| 50 |
+
self.opened_tool_calls: set[str] = set()
|
| 51 |
+
|
| 52 |
+
def ensure_message_start(self) -> None:
|
| 53 |
+
if not self.pending_chunks:
|
| 54 |
+
self.pending_chunks.append(_message_start_event(self.msg_id, self.model_name, self.prompt, ""))
|
| 55 |
+
|
| 56 |
+
def close_current_block(self) -> None:
|
| 57 |
+
index = self.current_block.get("index")
|
| 58 |
+
if index is None:
|
| 59 |
+
return
|
| 60 |
+
self.pending_chunks.append(stream_presenter.anthropic_content_block_stop(index))
|
| 61 |
+
self.current_block = {"type": None, "index": None, "tool_call_id": None}
|
| 62 |
+
|
| 63 |
+
def open_textual_block(self, block_type: str) -> int:
|
| 64 |
+
current_type = self.current_block.get("type")
|
| 65 |
+
current_index = self.current_block.get("index")
|
| 66 |
+
if current_type == block_type and isinstance(current_index, int):
|
| 67 |
+
return current_index
|
| 68 |
+
self.close_current_block()
|
| 69 |
+
index = self.block_index
|
| 70 |
+
self.block_index += 1
|
| 71 |
+
if block_type == "thinking":
|
| 72 |
+
content_block = {"type": "thinking", "thinking": ""}
|
| 73 |
+
else:
|
| 74 |
+
content_block = {"type": "text", "text": ""}
|
| 75 |
+
self.pending_chunks.append(stream_presenter.anthropic_content_block_start(index, content_block))
|
| 76 |
+
self.current_block = {"type": block_type, "index": index, "tool_call_id": None}
|
| 77 |
+
return index
|
| 78 |
+
|
| 79 |
+
def open_tool_block(self, tool_call_id: str, tool_name: str) -> int:
|
| 80 |
+
current_index = self.current_block.get("index")
|
| 81 |
+
if (
|
| 82 |
+
self.current_block.get("type") == "tool_use"
|
| 83 |
+
and self.current_block.get("tool_call_id") == tool_call_id
|
| 84 |
+
and isinstance(current_index, int)
|
| 85 |
+
):
|
| 86 |
+
return current_index
|
| 87 |
+
self.close_current_block()
|
| 88 |
+
index = self.block_index
|
| 89 |
+
self.block_index += 1
|
| 90 |
+
self.pending_chunks.append(
|
| 91 |
+
f"event: content_block_start\ndata: {json.dumps({'type': 'content_block_start', 'index': index, 'content_block': {'type': 'tool_use', 'id': tool_call_id, 'name': tool_name, 'input': {}}}, ensure_ascii=False)}\n\n"
|
| 92 |
+
)
|
| 93 |
+
self.current_block = {"type": "tool_use", "index": index, "tool_call_id": tool_call_id}
|
| 94 |
+
self.opened_tool_calls.add(tool_call_id)
|
| 95 |
+
return index
|
| 96 |
+
|
| 97 |
+
def append_thinking_delta(self, text_chunk: str) -> None:
|
| 98 |
+
index = self.open_textual_block("thinking")
|
| 99 |
+
self.pending_chunks.append(
|
| 100 |
+
stream_presenter.anthropic_content_block_delta(index, {"type": "thinking_delta", "thinking": text_chunk})
|
| 101 |
+
)
|
| 102 |
+
|
| 103 |
+
def buffer_answer_text(self, text_chunk: str) -> None:
|
| 104 |
+
index = self.open_textual_block("text")
|
| 105 |
+
self.answer_text_buffer.append((index, text_chunk))
|
| 106 |
+
|
| 107 |
+
def append_tool_delta(self, *, tool_call_id: str, tool_name: str, partial_json: str) -> None:
|
| 108 |
+
index = self.open_tool_block(tool_call_id, tool_name)
|
| 109 |
+
if partial_json:
|
| 110 |
+
self.pending_chunks.append(
|
| 111 |
+
stream_presenter.anthropic_content_block_delta(index, {"type": "input_json_delta", "partial_json": partial_json})
|
| 112 |
+
)
|
| 113 |
+
|
| 114 |
+
def flush_answer_text(self) -> None:
|
| 115 |
+
if not self.answer_text_buffer:
|
| 116 |
+
return
|
| 117 |
+
for index, text_chunk in self.answer_text_buffer:
|
| 118 |
+
self.pending_chunks.append(
|
| 119 |
+
stream_presenter.anthropic_content_block_delta(index, {"type": "text_delta", "text": text_chunk})
|
| 120 |
+
)
|
| 121 |
+
self.answer_text_buffer = []
|
| 122 |
+
|
| 123 |
+
def clear_answer_text(self) -> None:
|
| 124 |
+
self.answer_text_buffer = []
|
| 125 |
+
|
| 126 |
+
|
| 127 |
+
def _build_standard_request(req_data: dict) -> StandardRequest:
|
| 128 |
+
"""使用 CLIProxy 进行协议转换"""
|
| 129 |
+
standard_request = CLIProxy.from_anthropic(req_data, client_profile=CLAUDE_CODE_OPENAI_PROFILE)
|
| 130 |
+
CLIProxy.log_conversion("anthropic", standard_request.response_model, len(standard_request.prompt), len(standard_request.tools))
|
| 131 |
+
return standard_request
|
| 132 |
+
|
| 133 |
+
|
| 134 |
+
def _anthropic_usage(prompt: str, answer_text: str) -> dict[str, int]:
|
| 135 |
+
return {"input_tokens": len(prompt), "output_tokens": len(answer_text)}
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
def _message_start_event(msg_id: str, model_name: str, prompt: str, answer_text: str) -> str:
|
| 139 |
+
return stream_presenter.anthropic_message_start(msg_id, model_name, _anthropic_usage(prompt, answer_text))
|
| 140 |
+
|
| 141 |
+
|
| 142 |
+
async def _run_anthropic_attempt(
|
| 143 |
+
*,
|
| 144 |
+
client: QwenClient,
|
| 145 |
+
standard_request: StandardRequest,
|
| 146 |
+
current_prompt: str,
|
| 147 |
+
history_messages: list[dict],
|
| 148 |
+
stream_attempt: int,
|
| 149 |
+
max_attempts: int,
|
| 150 |
+
):
|
| 151 |
+
update_request_context(stream_attempt=stream_attempt + 1)
|
| 152 |
+
execution = await collect_completion_run(client, standard_request, current_prompt)
|
| 153 |
+
retry = evaluate_retry_directive(
|
| 154 |
+
request=standard_request,
|
| 155 |
+
current_prompt=current_prompt,
|
| 156 |
+
history_messages=history_messages,
|
| 157 |
+
attempt_index=stream_attempt,
|
| 158 |
+
max_attempts=max_attempts,
|
| 159 |
+
state=execution.state,
|
| 160 |
+
allow_after_visible_output=True,
|
| 161 |
+
)
|
| 162 |
+
return execution, retry
|
| 163 |
+
|
| 164 |
+
|
| 165 |
+
def _visible_answer_text_length(*, directive, execution, stream_state: _AnthropicStreamState | None = None) -> int:
|
| 166 |
+
if directive.stop_reason == "tool_use":
|
| 167 |
+
return 0
|
| 168 |
+
if stream_state is not None:
|
| 169 |
+
return sum(len(text_chunk) for _, text_chunk in stream_state.answer_text_buffer)
|
| 170 |
+
return len(execution.state.answer_text)
|
| 171 |
+
|
| 172 |
+
|
| 173 |
+
async def _add_used_tokens_for_prompt(*, users_db, token: str, prompt_text: str, answer_text_length: int) -> None:
|
| 174 |
+
users = await users_db.get()
|
| 175 |
+
for user in users:
|
| 176 |
+
if user["id"] == token:
|
| 177 |
+
user["used_tokens"] += answer_text_length + len(prompt_text)
|
| 178 |
+
break
|
| 179 |
+
await users_db.save(users)
|
| 180 |
+
|
| 181 |
+
|
| 182 |
+
async def _reacquire_bound_account_if_needed(*, client: QwenClient, standard_request: StandardRequest) -> None:
|
| 183 |
+
preferred_email = getattr(standard_request, "bound_account_email", None)
|
| 184 |
+
if preferred_email:
|
| 185 |
+
standard_request.bound_account = await client.account_pool.acquire_wait_preferred(preferred_email, timeout=60)
|
| 186 |
+
else:
|
| 187 |
+
standard_request.bound_account = None
|
| 188 |
+
|
| 189 |
+
|
| 190 |
+
@router.post("/messages/count_tokens")
|
| 191 |
+
@router.post("/v1/messages/count_tokens")
|
| 192 |
+
@router.post("/anthropic/v1/messages/count_tokens")
|
| 193 |
+
async def anthropic_count_tokens(request: Request):
|
| 194 |
+
try:
|
| 195 |
+
req_data = await request.json()
|
| 196 |
+
except Exception:
|
| 197 |
+
raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}})
|
| 198 |
+
prompt_result = messages_to_prompt(req_data, client_profile=CLAUDE_CODE_OPENAI_PROFILE)
|
| 199 |
+
base_tokens = count_tokens(prompt_result.prompt)
|
| 200 |
+
# Context Pressure Inflation:
|
| 201 |
+
# Claude Code 假设 context window=200K,到 ~80%(160K) 触发自动压缩。
|
| 202 |
+
# 但 Qwen 实际上游 window 只有 ~150K,到 ~120K 时就开始挤压输出预算。
|
| 203 |
+
# 虚增 input_tokens 1.35x 让 CC 提前触发压缩,避免爆 window。
|
| 204 |
+
inflation = 1.35
|
| 205 |
+
inflated = int(base_tokens * inflation)
|
| 206 |
+
return JSONResponse({"input_tokens": inflated})
|
| 207 |
+
|
| 208 |
+
|
| 209 |
+
@router.post("/messages")
|
| 210 |
+
@router.post("/v1/messages")
|
| 211 |
+
@router.post("/anthropic/v1/messages")
|
| 212 |
+
async def anthropic_messages(request: Request):
|
| 213 |
+
app = request.app
|
| 214 |
+
users_db = app.state.users_db
|
| 215 |
+
client: QwenClient = app.state.qwen_client
|
| 216 |
+
|
| 217 |
+
auth = await resolve_auth_context(request, users_db)
|
| 218 |
+
token = auth.token
|
| 219 |
+
|
| 220 |
+
try:
|
| 221 |
+
req_data = await request.json()
|
| 222 |
+
except Exception:
|
| 223 |
+
raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}})
|
| 224 |
+
|
| 225 |
+
session_key = derive_session_key("anthropic", token, req_data)
|
| 226 |
+
original_history_messages = req_data.get("messages", [])
|
| 227 |
+
|
| 228 |
+
async def prepare_locked_request(payload: dict) -> tuple[StandardRequest, dict, str, str, str, str]:
|
| 229 |
+
file_store = getattr(app.state, "file_store", None)
|
| 230 |
+
preprocessed = None
|
| 231 |
+
working_payload = payload
|
| 232 |
+
if file_store is not None:
|
| 233 |
+
preprocessed = await preprocess_attachments(working_payload, file_store, owner_token=token)
|
| 234 |
+
working_payload = preprocessed.payload
|
| 235 |
+
context_prepared = await prepare_context_attachments(
|
| 236 |
+
app=app,
|
| 237 |
+
payload=working_payload,
|
| 238 |
+
surface="anthropic",
|
| 239 |
+
auth_token=token,
|
| 240 |
+
client_profile=CLAUDE_CODE_OPENAI_PROFILE,
|
| 241 |
+
existing_attachments=(preprocessed.attachments if preprocessed is not None else None),
|
| 242 |
+
)
|
| 243 |
+
working_payload = context_prepared["payload"]
|
| 244 |
+
standard_request = _build_standard_request(working_payload)
|
| 245 |
+
if preprocessed is not None:
|
| 246 |
+
standard_request.attachments = preprocessed.attachments
|
| 247 |
+
standard_request.uploaded_file_ids = preprocessed.uploaded_file_ids
|
| 248 |
+
standard_request.upstream_files = context_prepared["upstream_files"]
|
| 249 |
+
standard_request.session_key = context_prepared["session_key"]
|
| 250 |
+
standard_request.context_mode = context_prepared["context_mode"]
|
| 251 |
+
standard_request.bound_account_email = context_prepared["bound_account_email"]
|
| 252 |
+
standard_request.bound_account = context_prepared["bound_account"]
|
| 253 |
+
|
| 254 |
+
session_plan = await plan_persistent_session_turn(app=app, request=standard_request, payload=working_payload, surface="anthropic")
|
| 255 |
+
if session_plan.enabled:
|
| 256 |
+
standard_request.persistent_session = True
|
| 257 |
+
standard_request.full_prompt = session_plan.full_prompt
|
| 258 |
+
standard_request.prompt = session_plan.prompt
|
| 259 |
+
standard_request.session_message_hashes = session_plan.current_hashes
|
| 260 |
+
standard_request.upstream_chat_id = session_plan.existing_chat_id if session_plan.reuse_chat else None
|
| 261 |
+
if standard_request.bound_account is None and session_plan.account_email:
|
| 262 |
+
standard_request.bound_account = await app.state.account_pool.acquire_wait_preferred(session_plan.account_email, timeout=60)
|
| 263 |
+
if standard_request.bound_account is not None:
|
| 264 |
+
standard_request.bound_account_email = standard_request.bound_account.email
|
| 265 |
+
elif standard_request.bound_account is not None and not standard_request.bound_account_email:
|
| 266 |
+
standard_request.bound_account_email = standard_request.bound_account.email
|
| 267 |
+
if standard_request.upstream_chat_id and standard_request.bound_account is None:
|
| 268 |
+
log_session_plan_reuse_cancelled(
|
| 269 |
+
request=standard_request,
|
| 270 |
+
planned_chat_id=session_plan.existing_chat_id,
|
| 271 |
+
reason="missing_bound_account",
|
| 272 |
+
)
|
| 273 |
+
standard_request.upstream_chat_id = None
|
| 274 |
+
standard_request.prompt = standard_request.full_prompt or standard_request.prompt
|
| 275 |
+
|
| 276 |
+
model_name = standard_request.response_model
|
| 277 |
+
qwen_model = standard_request.resolved_model
|
| 278 |
+
prompt = standard_request.prompt
|
| 279 |
+
msg_id = f"msg_{uuid.uuid4().hex[:12]}"
|
| 280 |
+
return standard_request, working_payload, model_name, qwen_model, prompt, msg_id
|
| 281 |
+
|
| 282 |
+
with request_context(req_id=new_request_id(), surface="anthropic", requested_model=req_data.get("model", "claude-3-5-sonnet"), resolved_model="-", api_key=auth.token):
|
| 283 |
+
if request.headers.get("x-debug-session-key"):
|
| 284 |
+
pass
|
| 285 |
+
|
| 286 |
+
if req_data.get("stream", False):
|
| 287 |
+
async def generate():
|
| 288 |
+
async with app.state.session_locks.hold(session_key):
|
| 289 |
+
standard_request, effective_payload, model_name, qwen_model, prompt, msg_id = await prepare_locked_request(req_data)
|
| 290 |
+
update_request_context(requested_model=model_name, resolved_model=qwen_model)
|
| 291 |
+
log.info(f"[ANT] model={qwen_model}, stream={standard_request.stream}, tool_enabled={standard_request.tool_enabled}, tools={[t.get('name') for t in standard_request.tools]}, prompt_len={len(prompt)}")
|
| 292 |
+
history_messages = original_history_messages
|
| 293 |
+
current_prompt = prompt
|
| 294 |
+
max_attempts = request_max_attempts(standard_request)
|
| 295 |
+
for stream_attempt in range(max_attempts):
|
| 296 |
+
stream_state = _AnthropicStreamState(msg_id=msg_id, model_name=model_name, prompt=current_prompt)
|
| 297 |
+
try:
|
| 298 |
+
update_request_context(stream_attempt=stream_attempt + 1)
|
| 299 |
+
|
| 300 |
+
async def on_delta(evt, text_chunk, _):
|
| 301 |
+
stream_state.ensure_message_start()
|
| 302 |
+
phase = evt.get("phase")
|
| 303 |
+
if text_chunk and phase in ("think", "thinking_summary"):
|
| 304 |
+
stream_state.append_thinking_delta(text_chunk)
|
| 305 |
+
return
|
| 306 |
+
if text_chunk and phase == "answer":
|
| 307 |
+
stream_state.buffer_answer_text(text_chunk)
|
| 308 |
+
return
|
| 309 |
+
if phase == "tool_call":
|
| 310 |
+
extra = evt.get("extra", {}) or {}
|
| 311 |
+
tool_call_id = extra.get("tool_call_id")
|
| 312 |
+
if tool_call_id is None:
|
| 313 |
+
tool_call_id = f"tc_idx_{extra.get('index', 0)}"
|
| 314 |
+
tool_name = extra.get("tool_name")
|
| 315 |
+
if not tool_name:
|
| 316 |
+
return
|
| 317 |
+
stream_state.append_tool_delta(
|
| 318 |
+
tool_call_id=str(tool_call_id),
|
| 319 |
+
tool_name=str(tool_name),
|
| 320 |
+
partial_json=evt.get("content", ""),
|
| 321 |
+
)
|
| 322 |
+
|
| 323 |
+
execution = await collect_completion_run_with_recovery(
|
| 324 |
+
client,
|
| 325 |
+
standard_request,
|
| 326 |
+
current_prompt,
|
| 327 |
+
capture_events=False,
|
| 328 |
+
on_delta=on_delta,
|
| 329 |
+
max_continuation=2,
|
| 330 |
+
warmup_chars=64,
|
| 331 |
+
guard_chars=96,
|
| 332 |
+
)
|
| 333 |
+
retry = evaluate_retry_directive(
|
| 334 |
+
request=standard_request,
|
| 335 |
+
current_prompt=current_prompt,
|
| 336 |
+
history_messages=history_messages,
|
| 337 |
+
attempt_index=stream_attempt,
|
| 338 |
+
max_attempts=max_attempts,
|
| 339 |
+
state=execution.state,
|
| 340 |
+
allow_after_visible_output=True,
|
| 341 |
+
)
|
| 342 |
+
if retry.retry:
|
| 343 |
+
reused_persistent_chat = bool(standard_request.persistent_session and standard_request.upstream_chat_id)
|
| 344 |
+
# 如果正在复用会话,重试时保留会话,避免删除后重建导致上下文丢失
|
| 345 |
+
preserve_chat = reused_persistent_chat
|
| 346 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat)
|
| 347 |
+
if reused_persistent_chat:
|
| 348 |
+
# 保留 upstream_chat_id,在同一会话中重试
|
| 349 |
+
# standard_request.session_chat_invalidated = True
|
| 350 |
+
# standard_request.upstream_chat_id = None
|
| 351 |
+
current_prompt = build_retry_rebase_prompt(standard_request, reason=retry.reason)
|
| 352 |
+
else:
|
| 353 |
+
current_prompt = retry.next_prompt
|
| 354 |
+
await _reacquire_bound_account_if_needed(client=client, standard_request=standard_request)
|
| 355 |
+
continue
|
| 356 |
+
|
| 357 |
+
if not stream_state.pending_chunks:
|
| 358 |
+
stream_state.pending_chunks.append(_message_start_event(msg_id, model_name, current_prompt, execution.state.answer_text))
|
| 359 |
+
|
| 360 |
+
stream_state.close_current_block()
|
| 361 |
+
directive = build_tool_directive(standard_request, execution.state)
|
| 362 |
+
if directive.stop_reason == "tool_use":
|
| 363 |
+
stream_state.clear_answer_text()
|
| 364 |
+
stream_state.current_block = {"type": None, "index": None, "tool_call_id": None}
|
| 365 |
+
else:
|
| 366 |
+
stream_state.flush_answer_text()
|
| 367 |
+
expected_tool_ids = {
|
| 368 |
+
block.get("id")
|
| 369 |
+
for block in directive.tool_blocks
|
| 370 |
+
if block.get("type") == "tool_use" and block.get("id")
|
| 371 |
+
}
|
| 372 |
+
for block in directive.tool_blocks:
|
| 373 |
+
if block.get("type") != "tool_use":
|
| 374 |
+
continue
|
| 375 |
+
tool_id = block.get("id")
|
| 376 |
+
if tool_id in stream_state.opened_tool_calls:
|
| 377 |
+
continue
|
| 378 |
+
index = stream_state.open_tool_block(str(tool_id), str(block.get("name", "")))
|
| 379 |
+
stream_state.pending_chunks.append(
|
| 380 |
+
stream_presenter.anthropic_content_block_delta(index, {'type': 'input_json_delta', 'partial_json': json.dumps(block.get('input', {}), ensure_ascii=False)})
|
| 381 |
+
)
|
| 382 |
+
stream_state.close_current_block()
|
| 383 |
+
|
| 384 |
+
visible_answer_length = _visible_answer_text_length(
|
| 385 |
+
directive=directive,
|
| 386 |
+
execution=execution,
|
| 387 |
+
stream_state=stream_state,
|
| 388 |
+
)
|
| 389 |
+
stop_reason = "tool_use" if expected_tool_ids else "end_turn"
|
| 390 |
+
stream_state.pending_chunks.append(stream_presenter.anthropic_message_delta(stop_reason, visible_answer_length))
|
| 391 |
+
stream_state.pending_chunks.append(stream_presenter.anthropic_message_stop())
|
| 392 |
+
|
| 393 |
+
await _add_used_tokens_for_prompt(
|
| 394 |
+
users_db=users_db,
|
| 395 |
+
token=token,
|
| 396 |
+
prompt_text=current_prompt,
|
| 397 |
+
answer_text_length=len(execution.state.answer_text),
|
| 398 |
+
)
|
| 399 |
+
assistant_message = build_anthropic_assistant_history_message(
|
| 400 |
+
execution=execution,
|
| 401 |
+
request=standard_request,
|
| 402 |
+
directive=directive,
|
| 403 |
+
)
|
| 404 |
+
await persist_session_turn(
|
| 405 |
+
app=app,
|
| 406 |
+
request=standard_request,
|
| 407 |
+
surface="anthropic",
|
| 408 |
+
execution=execution,
|
| 409 |
+
assistant_message=assistant_message,
|
| 410 |
+
)
|
| 411 |
+
await cleanup_runtime_resources(
|
| 412 |
+
client,
|
| 413 |
+
execution.acc,
|
| 414 |
+
execution.chat_id,
|
| 415 |
+
preserve_chat=bool(standard_request.persistent_session),
|
| 416 |
+
)
|
| 417 |
+
for chunk in stream_state.pending_chunks:
|
| 418 |
+
yield chunk
|
| 419 |
+
return
|
| 420 |
+
except HTTPException as he:
|
| 421 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 422 |
+
yield f"event: error\ndata: {json.dumps({'type': 'error', 'error': {'type': 'api_error', 'message': he.detail}}, ensure_ascii=False)}\n\n"
|
| 423 |
+
return
|
| 424 |
+
except Exception as e:
|
| 425 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 426 |
+
yield f"event: error\ndata: {json.dumps({'type': 'error', 'error': {'type': 'api_error', 'message': str(e)}}, ensure_ascii=False)}\n\n"
|
| 427 |
+
return
|
| 428 |
+
|
| 429 |
+
return StreamingResponse(
|
| 430 |
+
generate(),
|
| 431 |
+
media_type="text/event-stream",
|
| 432 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
| 433 |
+
)
|
| 434 |
+
|
| 435 |
+
async with app.state.session_locks.hold(session_key):
|
| 436 |
+
standard_request, effective_payload, model_name, qwen_model, prompt, msg_id = await prepare_locked_request(req_data)
|
| 437 |
+
update_request_context(requested_model=model_name, resolved_model=qwen_model)
|
| 438 |
+
log.info(f"[ANT] model={qwen_model}, stream={standard_request.stream}, tool_enabled={standard_request.tool_enabled}, tools={[t.get('name') for t in standard_request.tools]}, prompt_len={len(prompt)}")
|
| 439 |
+
history_messages = original_history_messages
|
| 440 |
+
current_prompt = prompt
|
| 441 |
+
max_attempts = request_max_attempts(standard_request)
|
| 442 |
+
for stream_attempt in range(max_attempts):
|
| 443 |
+
try:
|
| 444 |
+
execution, retry = await _run_anthropic_attempt(
|
| 445 |
+
client=client,
|
| 446 |
+
standard_request=standard_request,
|
| 447 |
+
current_prompt=current_prompt,
|
| 448 |
+
history_messages=history_messages,
|
| 449 |
+
stream_attempt=stream_attempt,
|
| 450 |
+
max_attempts=max_attempts,
|
| 451 |
+
)
|
| 452 |
+
if retry.retry:
|
| 453 |
+
reused_persistent_chat = bool(standard_request.persistent_session and standard_request.upstream_chat_id)
|
| 454 |
+
# 如果正在复用会话,重试时保留会话,避免删除后重建导致上下文丢失
|
| 455 |
+
preserve_chat = reused_persistent_chat
|
| 456 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat)
|
| 457 |
+
if reused_persistent_chat:
|
| 458 |
+
# 保留 upstream_chat_id,在同一会话中重试
|
| 459 |
+
# standard_request.session_chat_invalidated = True
|
| 460 |
+
# standard_request.upstream_chat_id = None
|
| 461 |
+
current_prompt = build_retry_rebase_prompt(standard_request, reason=retry.reason)
|
| 462 |
+
else:
|
| 463 |
+
current_prompt = retry.next_prompt
|
| 464 |
+
await _reacquire_bound_account_if_needed(client=client, standard_request=standard_request)
|
| 465 |
+
continue
|
| 466 |
+
|
| 467 |
+
directive = build_tool_directive(standard_request, execution.state)
|
| 468 |
+
content_blocks: list[dict] = []
|
| 469 |
+
if execution.state.reasoning_text:
|
| 470 |
+
content_blocks.append({"type": "thinking", "thinking": execution.state.reasoning_text})
|
| 471 |
+
content_blocks.extend(directive.tool_blocks)
|
| 472 |
+
|
| 473 |
+
await _add_used_tokens_for_prompt(
|
| 474 |
+
users_db=users_db,
|
| 475 |
+
token=token,
|
| 476 |
+
prompt_text=current_prompt,
|
| 477 |
+
answer_text_length=len(execution.state.answer_text),
|
| 478 |
+
)
|
| 479 |
+
assistant_message = build_anthropic_assistant_history_message(
|
| 480 |
+
execution=execution,
|
| 481 |
+
request=standard_request,
|
| 482 |
+
directive=directive,
|
| 483 |
+
)
|
| 484 |
+
await persist_session_turn(
|
| 485 |
+
app=app,
|
| 486 |
+
request=standard_request,
|
| 487 |
+
surface="anthropic",
|
| 488 |
+
execution=execution,
|
| 489 |
+
assistant_message=assistant_message,
|
| 490 |
+
)
|
| 491 |
+
await cleanup_runtime_resources(
|
| 492 |
+
client,
|
| 493 |
+
execution.acc,
|
| 494 |
+
execution.chat_id,
|
| 495 |
+
preserve_chat=bool(standard_request.persistent_session),
|
| 496 |
+
)
|
| 497 |
+
|
| 498 |
+
return JSONResponse(
|
| 499 |
+
{
|
| 500 |
+
"id": msg_id,
|
| 501 |
+
"type": "message",
|
| 502 |
+
"role": "assistant",
|
| 503 |
+
"model": model_name,
|
| 504 |
+
"content": content_blocks,
|
| 505 |
+
"stop_reason": directive.stop_reason,
|
| 506 |
+
"stop_sequence": None,
|
| 507 |
+
"usage": _anthropic_usage(current_prompt, execution.state.answer_text),
|
| 508 |
+
}
|
| 509 |
+
)
|
| 510 |
+
except Exception as e:
|
| 511 |
+
if stream_attempt == max_attempts - 1:
|
| 512 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 513 |
+
raise HTTPException(status_code=500, detail=str(e))
|
backend/api/embeddings.py
ADDED
|
@@ -0,0 +1,90 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Request, HTTPException
|
| 2 |
+
import json
|
| 3 |
+
import uuid
|
| 4 |
+
import logging
|
| 5 |
+
from backend.services.token_calc import count_tokens
|
| 6 |
+
|
| 7 |
+
log = logging.getLogger("qwen2api.embeddings")
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
@router.post("/embeddings")
|
| 11 |
+
@router.post("/v1/embeddings")
|
| 12 |
+
async def create_embeddings(request: Request):
|
| 13 |
+
"""
|
| 14 |
+
Embeddings 模拟/转发接口。
|
| 15 |
+
通义千问 Web 版没有原生的 Embeddings 接口。
|
| 16 |
+
为了兼容部分客户端强制验证 Embeddings 的情况(如 OpenWebUI 的某些场景),
|
| 17 |
+
这里提供基于 Tiktoken 和 Hash 的模拟响应,或配置专门的小模型转发。
|
| 18 |
+
目前实现为模拟返回。
|
| 19 |
+
"""
|
| 20 |
+
app = request.app
|
| 21 |
+
users_db = app.state.users_db
|
| 22 |
+
|
| 23 |
+
# 鉴权 (完全复原单文件逻辑)
|
| 24 |
+
auth_header = request.headers.get("Authorization", "")
|
| 25 |
+
token = auth_header[7:].strip() if auth_header.startswith("Bearer ") else ""
|
| 26 |
+
|
| 27 |
+
if not token:
|
| 28 |
+
token = request.headers.get("x-api-key", "").strip()
|
| 29 |
+
if not token:
|
| 30 |
+
token = request.query_params.get("key", "").strip() or request.query_params.get("api_key", "").strip()
|
| 31 |
+
|
| 32 |
+
from backend.core.config import API_KEYS, settings
|
| 33 |
+
admin_k = settings.ADMIN_KEY
|
| 34 |
+
|
| 35 |
+
if API_KEYS:
|
| 36 |
+
if token != admin_k and token not in API_KEYS and not token:
|
| 37 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 38 |
+
|
| 39 |
+
users = await users_db.get()
|
| 40 |
+
user = next((u for u in users if u["id"] == token), None)
|
| 41 |
+
if user and user.get("quota", 0) <= user.get("used_tokens", 0):
|
| 42 |
+
raise HTTPException(status_code=402, detail="Quota Exceeded")
|
| 43 |
+
|
| 44 |
+
body = await request.json()
|
| 45 |
+
model = body.get("model", "text-embedding-ada-002")
|
| 46 |
+
input_text = body.get("input", "")
|
| 47 |
+
|
| 48 |
+
if isinstance(input_text, str):
|
| 49 |
+
input_list = [input_text]
|
| 50 |
+
else:
|
| 51 |
+
input_list = input_text
|
| 52 |
+
|
| 53 |
+
data = []
|
| 54 |
+
total_tokens = 0
|
| 55 |
+
|
| 56 |
+
for i, text in enumerate(input_list):
|
| 57 |
+
tokens = count_tokens(text)
|
| 58 |
+
total_tokens += tokens
|
| 59 |
+
|
| 60 |
+
# 模拟生成 1536 维的特征向量
|
| 61 |
+
# 基于文本 hash 的简单确定性伪随机向量,保证同一文本结果一致
|
| 62 |
+
import hashlib
|
| 63 |
+
h = hashlib.sha256(text.encode('utf-8')).hexdigest()
|
| 64 |
+
base_val = int(h[:8], 16) / 0xffffffff
|
| 65 |
+
vector = [(base_val * (j % 10) / 10.0) - 0.5 for j in range(1536)]
|
| 66 |
+
|
| 67 |
+
data.append({
|
| 68 |
+
"object": "embedding",
|
| 69 |
+
"embedding": vector,
|
| 70 |
+
"index": i
|
| 71 |
+
})
|
| 72 |
+
|
| 73 |
+
usage = {
|
| 74 |
+
"prompt_tokens": total_tokens,
|
| 75 |
+
"total_tokens": total_tokens
|
| 76 |
+
}
|
| 77 |
+
|
| 78 |
+
# 异步扣除 Token
|
| 79 |
+
for u in users:
|
| 80 |
+
if u["id"] == token:
|
| 81 |
+
u["used_tokens"] += usage["total_tokens"]
|
| 82 |
+
break
|
| 83 |
+
await users_db.save(users)
|
| 84 |
+
|
| 85 |
+
return {
|
| 86 |
+
"object": "list",
|
| 87 |
+
"data": data,
|
| 88 |
+
"model": model,
|
| 89 |
+
"usage": usage
|
| 90 |
+
}
|
backend/api/files_api.py
ADDED
|
@@ -0,0 +1,77 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import os
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
|
| 6 |
+
from fastapi import APIRouter, File, HTTPException, Request, UploadFile
|
| 7 |
+
from fastapi.responses import JSONResponse
|
| 8 |
+
|
| 9 |
+
from backend.core.config import settings
|
| 10 |
+
from backend.services.auth_quota import resolve_auth_context
|
| 11 |
+
|
| 12 |
+
router = APIRouter()
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
def _allowed_exts() -> set[str]:
|
| 16 |
+
return {item.strip().lower() for item in settings.CONTEXT_ALLOWED_USER_EXTS.split(",") if item.strip()}
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
def _validate_upload(filename: str) -> None:
|
| 20 |
+
ext = Path(filename).suffix.lower().lstrip(".")
|
| 21 |
+
if not ext or ext not in _allowed_exts():
|
| 22 |
+
raise HTTPException(status_code=400, detail=f"Unsupported file extension: {ext or 'none'}")
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
@router.post("/api/files/upload")
|
| 26 |
+
@router.post("/v1/files")
|
| 27 |
+
async def upload_file(request: Request, file: UploadFile = File(...)):
|
| 28 |
+
app = request.app
|
| 29 |
+
users_db = app.state.users_db
|
| 30 |
+
auth = await resolve_auth_context(request, users_db)
|
| 31 |
+
token = auth.token
|
| 32 |
+
|
| 33 |
+
_validate_upload(file.filename or "")
|
| 34 |
+
raw = await file.read()
|
| 35 |
+
if not raw:
|
| 36 |
+
raise HTTPException(status_code=400, detail="Empty file")
|
| 37 |
+
|
| 38 |
+
file_store = app.state.file_store
|
| 39 |
+
meta = await file_store.save_bytes(
|
| 40 |
+
file.filename or "upload.bin",
|
| 41 |
+
file.content_type or "application/octet-stream",
|
| 42 |
+
raw,
|
| 43 |
+
"upload",
|
| 44 |
+
owner_token=token,
|
| 45 |
+
)
|
| 46 |
+
return JSONResponse({
|
| 47 |
+
"id": meta["id"],
|
| 48 |
+
"object": "file",
|
| 49 |
+
"filename": meta["filename"],
|
| 50 |
+
"bytes": meta["size"],
|
| 51 |
+
"content_type": meta["content_type"],
|
| 52 |
+
"created_at": meta["created_at"],
|
| 53 |
+
"content_block": {
|
| 54 |
+
"type": "input_file",
|
| 55 |
+
"file_id": meta["id"],
|
| 56 |
+
"filename": meta["filename"],
|
| 57 |
+
"mime_type": meta["content_type"],
|
| 58 |
+
},
|
| 59 |
+
})
|
| 60 |
+
|
| 61 |
+
|
| 62 |
+
@router.delete("/api/files/{file_id}")
|
| 63 |
+
@router.delete("/v1/files/{file_id}")
|
| 64 |
+
async def delete_file(request: Request, file_id: str):
|
| 65 |
+
app = request.app
|
| 66 |
+
users_db = app.state.users_db
|
| 67 |
+
auth = await resolve_auth_context(request, users_db)
|
| 68 |
+
token = auth.token
|
| 69 |
+
|
| 70 |
+
file_store = app.state.file_store
|
| 71 |
+
meta = await file_store.get(file_id)
|
| 72 |
+
if meta is None:
|
| 73 |
+
raise HTTPException(status_code=404, detail="File not found")
|
| 74 |
+
if meta.get("owner_token") and meta.get("owner_token") != token:
|
| 75 |
+
raise HTTPException(status_code=403, detail="Forbidden")
|
| 76 |
+
await file_store.delete(file_id)
|
| 77 |
+
return {"deleted": True, "id": file_id}
|
backend/api/gemini.py
ADDED
|
@@ -0,0 +1,145 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Request, HTTPException
|
| 2 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 3 |
+
import asyncio
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from backend.adapter.standard_request import StandardRequest
|
| 9 |
+
from backend.adapter.cli_proxy import CLIProxy
|
| 10 |
+
from backend.core.config import resolve_model
|
| 11 |
+
from backend.core.request_logging import new_request_id, request_context, update_request_context
|
| 12 |
+
from backend.runtime import stream_presenter
|
| 13 |
+
from backend.runtime.execution import collect_completion_run, cleanup_runtime_resources
|
| 14 |
+
from backend.services.auth_quota import resolve_auth_context
|
| 15 |
+
from backend.services.token_calc import calculate_usage
|
| 16 |
+
|
| 17 |
+
log = logging.getLogger("qwen2api.gemini")
|
| 18 |
+
router = APIRouter()
|
| 19 |
+
|
| 20 |
+
GEMINI_STREAM_MEDIA_TYPE = "application/json"
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
def _build_standard_request(model: str, body: dict, *, stream: bool | None = None) -> StandardRequest:
|
| 24 |
+
"""使用 CLIProxy 进行协议转换"""
|
| 25 |
+
standard_request = CLIProxy.from_gemini(model, body, stream=stream)
|
| 26 |
+
CLIProxy.log_conversion("gemini", standard_request.response_model, len(standard_request.prompt), len(standard_request.tools))
|
| 27 |
+
return standard_request
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
def _gemini_chunk_payload(text: str) -> dict[str, Any]:
|
| 31 |
+
return {
|
| 32 |
+
"candidates": [
|
| 33 |
+
{
|
| 34 |
+
"content": {
|
| 35 |
+
"parts": [{"text": text}],
|
| 36 |
+
"role": "model",
|
| 37 |
+
}
|
| 38 |
+
}
|
| 39 |
+
]
|
| 40 |
+
}
|
| 41 |
+
|
| 42 |
+
|
| 43 |
+
async def _load_and_validate_request(request: Request, model: str, *, force_stream: bool | None = None):
|
| 44 |
+
app = request.app
|
| 45 |
+
users_db = app.state.users_db
|
| 46 |
+
client = app.state.qwen_client
|
| 47 |
+
|
| 48 |
+
auth = await resolve_auth_context(request, users_db)
|
| 49 |
+
token = auth.token
|
| 50 |
+
|
| 51 |
+
body = await request.json()
|
| 52 |
+
standard_request = _build_standard_request(model, body, stream=force_stream)
|
| 53 |
+
update_request_context(resolved_model=standard_request.resolved_model)
|
| 54 |
+
return users_db, client, token, standard_request
|
| 55 |
+
|
| 56 |
+
|
| 57 |
+
@router.post("/v1beta/models/{model}:generateContent")
|
| 58 |
+
@router.post("/v1/models/{model}:generateContent")
|
| 59 |
+
@router.post("/models/{model}:generateContent")
|
| 60 |
+
async def gemini_generate_content(model: str, request: Request):
|
| 61 |
+
with request_context(req_id=new_request_id(), surface="gemini", requested_model=model):
|
| 62 |
+
users_db, client, token, standard_request = await _load_and_validate_request(request, model, force_stream=False)
|
| 63 |
+
content = standard_request.prompt
|
| 64 |
+
log.info(f"[Gemini] route=generateContent model={standard_request.resolved_model}, stream={standard_request.stream}, prompt_len={len(content)}")
|
| 65 |
+
|
| 66 |
+
try:
|
| 67 |
+
execution = await collect_completion_run(client, standard_request, content)
|
| 68 |
+
except Exception as e:
|
| 69 |
+
log.error(f"Gemini proxy failed: {e}")
|
| 70 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 71 |
+
|
| 72 |
+
usage = calculate_usage(content, execution.state.answer_text)
|
| 73 |
+
users = await users_db.get()
|
| 74 |
+
for u in users:
|
| 75 |
+
if u["id"] == token:
|
| 76 |
+
u["used_tokens"] += usage["total_tokens"]
|
| 77 |
+
break
|
| 78 |
+
await users_db.save(users)
|
| 79 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id)
|
| 80 |
+
|
| 81 |
+
log.info(f"[Gemini] Request complete. Generated {len(execution.state.answer_text)} characters.")
|
| 82 |
+
return JSONResponse(
|
| 83 |
+
{
|
| 84 |
+
"candidates": [
|
| 85 |
+
{
|
| 86 |
+
"content": {
|
| 87 |
+
"parts": [{"text": execution.state.answer_text}],
|
| 88 |
+
"role": "model",
|
| 89 |
+
}
|
| 90 |
+
}
|
| 91 |
+
]
|
| 92 |
+
}
|
| 93 |
+
)
|
| 94 |
+
|
| 95 |
+
|
| 96 |
+
@router.post("/v1beta/models/{model}:streamGenerateContent")
|
| 97 |
+
@router.post("/v1/models/{model}:streamGenerateContent")
|
| 98 |
+
@router.post("/models/{model}:streamGenerateContent")
|
| 99 |
+
async def gemini_stream_generate_content(model: str, request: Request):
|
| 100 |
+
with request_context(req_id=new_request_id(), surface="gemini", requested_model=model):
|
| 101 |
+
users_db, client, token, standard_request = await _load_and_validate_request(request, model, force_stream=True)
|
| 102 |
+
content = standard_request.prompt
|
| 103 |
+
log.info(f"[Gemini] route=streamGenerateContent model={standard_request.resolved_model}, stream={standard_request.stream}, prompt_len={len(content)}")
|
| 104 |
+
|
| 105 |
+
async def generate():
|
| 106 |
+
queue: asyncio.Queue[str | None] = asyncio.Queue()
|
| 107 |
+
|
| 108 |
+
async def on_delta(evt, text_chunk, _):
|
| 109 |
+
if text_chunk and evt.get("phase") == "answer":
|
| 110 |
+
await queue.put(stream_presenter.gemini_text_chunk(text_chunk))
|
| 111 |
+
|
| 112 |
+
async def runner():
|
| 113 |
+
execution = None
|
| 114 |
+
try:
|
| 115 |
+
execution = await collect_completion_run(
|
| 116 |
+
client,
|
| 117 |
+
standard_request,
|
| 118 |
+
content,
|
| 119 |
+
capture_events=False,
|
| 120 |
+
on_delta=on_delta,
|
| 121 |
+
)
|
| 122 |
+
|
| 123 |
+
usage = calculate_usage(content, execution.state.answer_text)
|
| 124 |
+
users = await users_db.get()
|
| 125 |
+
for u in users:
|
| 126 |
+
if u["id"] == token:
|
| 127 |
+
u["used_tokens"] += usage["total_tokens"]
|
| 128 |
+
break
|
| 129 |
+
await users_db.save(users)
|
| 130 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id)
|
| 131 |
+
log.info(f"[Gemini] Request complete. Generated {len(execution.state.answer_text)} characters.")
|
| 132 |
+
except Exception as e:
|
| 133 |
+
await queue.put(json.dumps({"error": str(e)}) + "\n")
|
| 134 |
+
finally:
|
| 135 |
+
await queue.put(None)
|
| 136 |
+
|
| 137 |
+
task = asyncio.create_task(runner())
|
| 138 |
+
while True:
|
| 139 |
+
chunk = await queue.get()
|
| 140 |
+
if chunk is None:
|
| 141 |
+
break
|
| 142 |
+
yield chunk
|
| 143 |
+
await task
|
| 144 |
+
|
| 145 |
+
return StreamingResponse(generate(), media_type=GEMINI_STREAM_MED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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
图片生成接口 — 兼容 OpenAI /v1/images/generations 与 /v1/images/edits。
|
| 3 |
+
|
| 4 |
+
- generations: 文生图 t2i
|
| 5 |
+
- edits: 图生图 i2i(参考角色/场景 sheet 生成分镜,供 ArcReel 使用)
|
| 6 |
+
|
| 7 |
+
优先走与视频相同的 HTTP 直连 complete_once,
|
| 8 |
+
避免依赖 Playwright 浏览器路径(易超时)。
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
from __future__ import annotations
|
| 12 |
+
|
| 13 |
+
import asyncio
|
| 14 |
+
import base64
|
| 15 |
+
import json
|
| 16 |
+
import logging
|
| 17 |
+
import mimetypes
|
| 18 |
+
import os
|
| 19 |
+
import re
|
| 20 |
+
import time
|
| 21 |
+
from typing import Any
|
| 22 |
+
|
| 23 |
+
import httpx
|
| 24 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 25 |
+
from fastapi.responses import JSONResponse
|
| 26 |
+
|
| 27 |
+
from backend.services.qwen_client import QwenClient
|
| 28 |
+
|
| 29 |
+
log = logging.getLogger("qwen2api.images")
|
| 30 |
+
router = APIRouter()
|
| 31 |
+
|
| 32 |
+
# 注意:chat.qwen.ai 网页侧没有独立的“专用生图模型 ID”,
|
| 33 |
+
# t2i 实际是聊天模型挂载 image_gen/t2i 能力。默认改用更高档模型。
|
| 34 |
+
DEFAULT_IMAGE_MODEL = "qwen3.7-max"
|
| 35 |
+
|
| 36 |
+
IMAGE_MODEL_MAP = {
|
| 37 |
+
"dall-e-3": "qwen3.7-max",
|
| 38 |
+
"dall-e-2": "qwen3.6-plus",
|
| 39 |
+
"qwen-image": "qwen3.7-max",
|
| 40 |
+
"qwen-image-plus": "qwen3.7-max",
|
| 41 |
+
"qwen-image-max": "qwen3.8-max-preview",
|
| 42 |
+
"qwen-image-turbo": "qwen3.6-plus",
|
| 43 |
+
"qwen3.6-plus": "qwen3.6-plus",
|
| 44 |
+
"qwen3.6-max-preview": "qwen3.6-max-preview",
|
| 45 |
+
"qwen3.7-plus": "qwen3.7-plus",
|
| 46 |
+
"qwen3.7-max": "qwen3.7-max",
|
| 47 |
+
"qwen3.8-max-preview": "qwen3.8-max-preview",
|
| 48 |
+
"qwen3.8": "qwen3.8-max-preview",
|
| 49 |
+
}
|
| 50 |
+
|
| 51 |
+
HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]+", re.IGNORECASE)
|
| 52 |
+
IMAGE_EXT_RE = re.compile(r"\.(?:jpg|jpeg|png|webp|gif)(?:[?#]|$)", re.IGNORECASE)
|
| 53 |
+
|
| 54 |
+
|
| 55 |
+
def _extract_image_urls(value: Any) -> list[str]:
|
| 56 |
+
urls: list[str] = []
|
| 57 |
+
|
| 58 |
+
def walk(v: Any, key_hint: str = ""):
|
| 59 |
+
if v is None:
|
| 60 |
+
return
|
| 61 |
+
if isinstance(v, str):
|
| 62 |
+
# markdown images
|
| 63 |
+
for u in re.findall(r"!\[.*?\]\((https?://[^\s\)]+)\)", v):
|
| 64 |
+
urls.append(u.rstrip(").,;"))
|
| 65 |
+
for u in HTTP_URL_RE.findall(v):
|
| 66 |
+
u2 = u.rstrip(".,;)\"'>")
|
| 67 |
+
low = u2.lower()
|
| 68 |
+
hint = key_hint.lower()
|
| 69 |
+
if IMAGE_EXT_RE.search(low) or any(x in low for x in ("cdn.qwenlm.ai", "alicdn.com", "/image", "img")):
|
| 70 |
+
if not any(x in low for x in (".mp4", ".webm", ".mov")):
|
| 71 |
+
urls.append(u2)
|
| 72 |
+
elif any(x in hint for x in ("image", "url", "src", "thumb")) and u2.startswith("http"):
|
| 73 |
+
if not any(x in low for x in (".mp4", ".webm", ".mov")):
|
| 74 |
+
urls.append(u2)
|
| 75 |
+
return
|
| 76 |
+
if isinstance(v, list):
|
| 77 |
+
for item in v:
|
| 78 |
+
walk(item, key_hint)
|
| 79 |
+
return
|
| 80 |
+
if isinstance(v, dict):
|
| 81 |
+
for k, item in v.items():
|
| 82 |
+
walk(item, str(k))
|
| 83 |
+
|
| 84 |
+
walk(value)
|
| 85 |
+
|
| 86 |
+
seen: set[str] = set()
|
| 87 |
+
out: list[str] = []
|
| 88 |
+
for u in urls:
|
| 89 |
+
if u not in seen:
|
| 90 |
+
seen.add(u)
|
| 91 |
+
out.append(u)
|
| 92 |
+
return out
|
| 93 |
+
|
| 94 |
+
|
| 95 |
+
def _extract_task_ids(value: Any) -> list[str]:
|
| 96 |
+
ids: list[str] = []
|
| 97 |
+
|
| 98 |
+
def walk(v: Any):
|
| 99 |
+
if v is None:
|
| 100 |
+
return
|
| 101 |
+
if isinstance(v, list):
|
| 102 |
+
for item in v:
|
| 103 |
+
walk(item)
|
| 104 |
+
return
|
| 105 |
+
if isinstance(v, dict):
|
| 106 |
+
for k, item in v.items():
|
| 107 |
+
if k in {"task_id", "taskId"} and isinstance(item, str) and item.strip():
|
| 108 |
+
ids.append(item.strip())
|
| 109 |
+
else:
|
| 110 |
+
walk(item)
|
| 111 |
+
|
| 112 |
+
walk(value)
|
| 113 |
+
# de-dupe
|
| 114 |
+
seen: set[str] = set()
|
| 115 |
+
out: list[str] = []
|
| 116 |
+
for i in ids:
|
| 117 |
+
if i not in seen:
|
| 118 |
+
seen.add(i)
|
| 119 |
+
out.append(i)
|
| 120 |
+
return out
|
| 121 |
+
|
| 122 |
+
|
| 123 |
+
def _resolve_image_model(requested: str | None) -> str:
|
| 124 |
+
if not requested:
|
| 125 |
+
return DEFAULT_IMAGE_MODEL
|
| 126 |
+
return IMAGE_MODEL_MAP.get(requested, DEFAULT_IMAGE_MODEL)
|
| 127 |
+
|
| 128 |
+
|
| 129 |
+
def _get_token(request: Request) -> str:
|
| 130 |
+
auth = request.headers.get("Authorization", "")
|
| 131 |
+
if auth.startswith("Bearer "):
|
| 132 |
+
return auth[7:].strip()
|
| 133 |
+
return request.headers.get("x-api-key", "").strip()
|
| 134 |
+
|
| 135 |
+
|
| 136 |
+
def _build_image_prompt(prompt: str) -> str:
|
| 137 |
+
return (
|
| 138 |
+
"Generate an image now. Return an accessible image URL if possible. "
|
| 139 |
+
"Do not only describe the image in words.\n\n"
|
| 140 |
+
f"User request: {prompt}"
|
| 141 |
+
)
|
| 142 |
+
|
| 143 |
+
|
| 144 |
+
async def _poll_image_task(client: QwenClient, token: str, task_id: str, *, timeout_seconds: int = 300) -> dict:
|
| 145 |
+
started = time.monotonic()
|
| 146 |
+
last: dict = {}
|
| 147 |
+
while time.monotonic() - started < timeout_seconds:
|
| 148 |
+
task_status = await client.get_task_status(token, task_id)
|
| 149 |
+
last = task_status if isinstance(task_status, dict) else {}
|
| 150 |
+
data = last.get("data") if isinstance(last.get("data"), dict) else last
|
| 151 |
+
state = str((data or {}).get("task_status") or (data or {}).get("status") or "").lower()
|
| 152 |
+
log.info("[T2I] task_id=%s status=%s", task_id, state)
|
| 153 |
+
if state == "success":
|
| 154 |
+
return last
|
| 155 |
+
if state not in {"running", "pending", "queued", "created", "processing", ""}:
|
| 156 |
+
raise HTTPException(status_code=500, detail={"message": "Image task failed", "task_status": data})
|
| 157 |
+
await asyncio.sleep(5)
|
| 158 |
+
raise HTTPException(status_code=504, detail={"message": "Image task timed out", "task_id": task_id, "last_status": last})
|
| 159 |
+
|
| 160 |
+
|
| 161 |
+
@router.post("/v1/images/generations")
|
| 162 |
+
@router.post("/images/generations")
|
| 163 |
+
async def create_image(request: Request):
|
| 164 |
+
from backend.core.config import API_KEYS, settings
|
| 165 |
+
|
| 166 |
+
client: QwenClient = request.app.state.qwen_client
|
| 167 |
+
|
| 168 |
+
token = _get_token(request)
|
| 169 |
+
if API_KEYS:
|
| 170 |
+
if token != settings.ADMIN_KEY and token not in API_KEYS:
|
| 171 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 172 |
+
|
| 173 |
+
try:
|
| 174 |
+
body = await request.json()
|
| 175 |
+
except Exception:
|
| 176 |
+
raise HTTPException(status_code=400, detail="Invalid JSON body")
|
| 177 |
+
|
| 178 |
+
prompt: str = str(body.get("prompt", "")).strip()
|
| 179 |
+
if not prompt:
|
| 180 |
+
raise HTTPException(status_code=400, detail="prompt is required")
|
| 181 |
+
|
| 182 |
+
n: int = min(max(int(body.get("n", 1)), 1), 4)
|
| 183 |
+
model = _resolve_image_model(body.get("model"))
|
| 184 |
+
size = str(body.get("size", "")).strip() or None
|
| 185 |
+
|
| 186 |
+
log.info("[T2I] model=%s n=%s size=%s prompt=%r", model, n, size, prompt[:100])
|
| 187 |
+
|
| 188 |
+
acc = None
|
| 189 |
+
chat_id = None
|
| 190 |
+
try:
|
| 191 |
+
prompt_text = _build_image_prompt(prompt)
|
| 192 |
+
|
| 193 |
+
# 1) Prefer same HTTP path as videos: create_chat(t2i) + complete_once
|
| 194 |
+
if client.account_pool is None:
|
| 195 |
+
raise HTTPException(status_code=500, detail="No upstream account pool configured")
|
| 196 |
+
|
| 197 |
+
acc = await client.account_pool.acquire_wait(timeout=30)
|
| 198 |
+
if acc is None:
|
| 199 |
+
raise HTTPException(status_code=503, detail="No available upstream accounts")
|
| 200 |
+
|
| 201 |
+
# Try t2i first; some deployments may only honor image mode via t2i chat_type
|
| 202 |
+
chat_type = "t2i"
|
| 203 |
+
try:
|
| 204 |
+
chat_id = await client.create_chat(acc.token, model, chat_type=chat_type)
|
| 205 |
+
except Exception as e:
|
| 206 |
+
log.warning("[T2I] create_chat t2i failed (%s), fallback t2t", e)
|
| 207 |
+
chat_type = "t2t"
|
| 208 |
+
chat_id = await client.create_chat(acc.token, model, chat_type=chat_type)
|
| 209 |
+
|
| 210 |
+
log.info("[T2I] chat_id=%s account=%s chat_type=%s", chat_id, getattr(acc, "email", ""), chat_type)
|
| 211 |
+
|
| 212 |
+
completion = await client.complete_once(
|
| 213 |
+
acc.token,
|
| 214 |
+
chat_id,
|
| 215 |
+
model,
|
| 216 |
+
prompt_text,
|
| 217 |
+
has_custom_tools=False,
|
| 218 |
+
chat_type=chat_type,
|
| 219 |
+
size=size,
|
| 220 |
+
)
|
| 221 |
+
|
| 222 |
+
search_payload: list[Any] = [completion]
|
| 223 |
+
try:
|
| 224 |
+
chat_detail = await client.get_chat(acc.token, chat_id)
|
| 225 |
+
search_payload.append(chat_detail)
|
| 226 |
+
except Exception as chat_error:
|
| 227 |
+
log.warning("[T2I] get_chat failed: %s", chat_error)
|
| 228 |
+
|
| 229 |
+
task_ids = _extract_task_ids(search_payload)
|
| 230 |
+
if task_ids:
|
| 231 |
+
log.info("[T2I] task IDs: %s", task_ids)
|
| 232 |
+
task_result = await _poll_image_task(client, acc.token, task_ids[0])
|
| 233 |
+
search_payload.append(task_result)
|
| 234 |
+
|
| 235 |
+
image_urls = _extract_image_urls(search_payload)
|
| 236 |
+
log.info("[T2I] extracted %s image URLs: %s", len(image_urls), image_urls[:5])
|
| 237 |
+
|
| 238 |
+
if not image_urls:
|
| 239 |
+
# fallback: old stream path (may need playwright)
|
| 240 |
+
log.warning("[T2I] HTTP path got no image URL, trying stream fallback")
|
| 241 |
+
event_payloads: list[str] = []
|
| 242 |
+
async for item in client.chat_stream_events_with_retry(model, prompt_text, has_custom_tools=False):
|
| 243 |
+
if item.get("type") == "event":
|
| 244 |
+
event_payloads.append(json.dumps(item.get("event", {}), ensure_ascii=False))
|
| 245 |
+
image_urls = _extract_image_urls("\n".join(event_payloads))
|
| 246 |
+
|
| 247 |
+
if not image_urls:
|
| 248 |
+
debug_path = (
|
| 249 |
+
__import__("os").path.join(
|
| 250 |
+
__import__("os").path.dirname(__import__("os").path.dirname(__import__("os").path.dirname(__file__))),
|
| 251 |
+
"logs",
|
| 252 |
+
"t2i-last-debug.json",
|
| 253 |
+
)
|
| 254 |
+
)
|
| 255 |
+
try:
|
| 256 |
+
with open(debug_path, "w", encoding="utf-8") as f:
|
| 257 |
+
json.dump({"completion": completion, "search": search_payload}, f, ensure_ascii=False, indent=2)
|
| 258 |
+
except Exception:
|
| 259 |
+
pass
|
| 260 |
+
raise HTTPException(status_code=500, detail="Image generation succeeded but no URL found")
|
| 261 |
+
|
| 262 |
+
# 默认返回 b64_json:ArcReel 等 Docker 容器常无法稳定下载 cdn.qwenlm.ai,
|
| 263 |
+
# 由宿主机网关下载后转 base64,可避免容器二次拉 CDN 失败。
|
| 264 |
+
response_format = str(body.get("response_format", "b64_json") or "b64_json").lower()
|
| 265 |
+
selected = image_urls[:n]
|
| 266 |
+
data: list[dict[str, Any]] = []
|
| 267 |
+
if response_format == "url":
|
| 268 |
+
data = [{"url": url, "revised_prompt": prompt} for url in selected]
|
| 269 |
+
else:
|
| 270 |
+
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as http:
|
| 271 |
+
for url in selected:
|
| 272 |
+
item: dict[str, Any] = {"url": url, "revised_prompt": prompt}
|
| 273 |
+
try:
|
| 274 |
+
resp = await http.get(url)
|
| 275 |
+
resp.raise_for_status()
|
| 276 |
+
item["b64_json"] = base64.b64encode(resp.content).decode("ascii")
|
| 277 |
+
except Exception as dl_err:
|
| 278 |
+
log.warning("[T2I] download for b64 failed url=%s err=%s", url[:120], dl_err)
|
| 279 |
+
data.append(item)
|
| 280 |
+
if not any(x.get("b64_json") for x in data):
|
| 281 |
+
# 全部下载失败时退回纯 URL,至少不让接口 500
|
| 282 |
+
log.warning("[T2I] all b64 downloads failed, fallback to url-only response")
|
| 283 |
+
return JSONResponse({"created": int(time.time()), "data": data})
|
| 284 |
+
|
| 285 |
+
except HTTPException:
|
| 286 |
+
raise
|
| 287 |
+
except Exception as e:
|
| 288 |
+
log.error("[T2I] generation failed: %s", e)
|
| 289 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 290 |
+
finally:
|
| 291 |
+
if acc is not None:
|
| 292 |
+
try:
|
| 293 |
+
client.account_pool.release(acc)
|
| 294 |
+
except Exception:
|
| 295 |
+
pass
|
| 296 |
+
if chat_id:
|
| 297 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
def _build_i2i_prompt(prompt: str) -> str:
|
| 301 |
+
return (
|
| 302 |
+
"Image-to-image edit / storyboard frame generation. "
|
| 303 |
+
"STRICTLY keep the same character identity, face, hairstyle, clothing colors, "
|
| 304 |
+
"art style and overall look from the attached reference image(s). "
|
| 305 |
+
"Only change pose, camera angle, composition and scene details as requested. "
|
| 306 |
+
"Generate an image now and return an accessible image URL if possible. "
|
| 307 |
+
"Do not only describe the image in words.\n\n"
|
| 308 |
+
f"User request: {prompt}"
|
| 309 |
+
)
|
| 310 |
+
|
| 311 |
+
|
| 312 |
+
async def _upload_i2i_refs(client: QwenClient, acc: Any, raw_files: list[tuple[bytes, str, str]]) -> list[dict]:
|
| 313 |
+
"""Upload local image bytes and build vision file refs for complete_once(files=...)."""
|
| 314 |
+
from backend.core.config import settings
|
| 315 |
+
from backend.services.upstream_file_uploader import UpstreamFileUploader
|
| 316 |
+
|
| 317 |
+
uploader = UpstreamFileUploader(client, settings)
|
| 318 |
+
out: list[dict] = []
|
| 319 |
+
tmp_dir = os.path.join(
|
| 320 |
+
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
| 321 |
+
"logs",
|
| 322 |
+
"image_refs",
|
| 323 |
+
)
|
| 324 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 325 |
+
|
| 326 |
+
for idx, (raw, content_type, filename) in enumerate(raw_files[:4]):
|
| 327 |
+
local_path = os.path.join(tmp_dir, f"{int(time.time())}_{idx}_{filename}")
|
| 328 |
+
with open(local_path, "wb") as f:
|
| 329 |
+
f.write(raw)
|
| 330 |
+
meta = {
|
| 331 |
+
"filename": filename,
|
| 332 |
+
"path": local_path,
|
| 333 |
+
"content_type": content_type,
|
| 334 |
+
"size": len(raw),
|
| 335 |
+
}
|
| 336 |
+
remote = await uploader.upload_local_file(acc, meta)
|
| 337 |
+
ref = remote.get("remote_ref")
|
| 338 |
+
put_url = ""
|
| 339 |
+
if isinstance(ref, dict):
|
| 340 |
+
put_url = str(ref.get("url") or "")
|
| 341 |
+
if not put_url:
|
| 342 |
+
put_url = str(remote.get("url") or "")
|
| 343 |
+
|
| 344 |
+
vision_ref: dict[str, Any] = {
|
| 345 |
+
"type": "image",
|
| 346 |
+
"name": filename,
|
| 347 |
+
"file_type": content_type if content_type.startswith("image/") else "image/png",
|
| 348 |
+
"showType": "image",
|
| 349 |
+
"status": "uploaded",
|
| 350 |
+
"file_class": "vision",
|
| 351 |
+
"url": put_url,
|
| 352 |
+
}
|
| 353 |
+
if isinstance(ref, dict):
|
| 354 |
+
if ref.get("id"):
|
| 355 |
+
vision_ref["id"] = ref.get("id")
|
| 356 |
+
if isinstance(ref.get("file"), dict) and ref["file"].get("id"):
|
| 357 |
+
vision_ref["file"] = ref["file"]
|
| 358 |
+
for k in ("itemId", "uploadTaskId", "size", "greenNet", "progress", "error", "collection_name"):
|
| 359 |
+
if k in ref and k not in vision_ref:
|
| 360 |
+
vision_ref[k] = ref[k]
|
| 361 |
+
if not vision_ref.get("url"):
|
| 362 |
+
log.warning("[I2I] upload missing url, remote=%s", remote)
|
| 363 |
+
out.append(vision_ref)
|
| 364 |
+
log.info(
|
| 365 |
+
"[I2I] uploaded ref name=%s url=%s",
|
| 366 |
+
filename,
|
| 367 |
+
(vision_ref.get("url") or "")[:120],
|
| 368 |
+
)
|
| 369 |
+
return out
|
| 370 |
+
|
| 371 |
+
|
| 372 |
+
async def _pack_image_response(
|
| 373 |
+
image_urls: list[str],
|
| 374 |
+
*,
|
| 375 |
+
prompt: str,
|
| 376 |
+
n: int,
|
| 377 |
+
response_format: str,
|
| 378 |
+
) -> JSONResponse:
|
| 379 |
+
selected = image_urls[:n]
|
| 380 |
+
data: list[dict[str, Any]] = []
|
| 381 |
+
if response_format == "url":
|
| 382 |
+
data = [{"url": url, "revised_prompt": prompt} for url in selected]
|
| 383 |
+
else:
|
| 384 |
+
async with httpx.AsyncClient(timeout=60.0, follow_redirects=True) as http:
|
| 385 |
+
for url in selected:
|
| 386 |
+
item: dict[str, Any] = {"url": url, "revised_prompt": prompt}
|
| 387 |
+
try:
|
| 388 |
+
resp = await http.get(url)
|
| 389 |
+
resp.raise_for_status()
|
| 390 |
+
item["b64_json"] = base64.b64encode(resp.content).decode("ascii")
|
| 391 |
+
except Exception as dl_err:
|
| 392 |
+
log.warning("[I2I] download for b64 failed url=%s err=%s", url[:120], dl_err)
|
| 393 |
+
data.append(item)
|
| 394 |
+
if not any(x.get("b64_json") for x in data):
|
| 395 |
+
log.warning("[I2I] all b64 downloads failed, fallback to url-only response")
|
| 396 |
+
return JSONResponse({"created": int(time.time()), "data": data})
|
| 397 |
+
|
| 398 |
+
|
| 399 |
+
@router.post("/v1/images/edits")
|
| 400 |
+
@router.post("/images/edits")
|
| 401 |
+
async def edit_image(request: Request):
|
| 402 |
+
"""OpenAI-compatible image edits (i2i).
|
| 403 |
+
|
| 404 |
+
Accepts multipart form (OpenAI SDK style) or JSON with image/images fields.
|
| 405 |
+
Uses Qwen vision + t2i tool path with attached reference image(s).
|
| 406 |
+
"""
|
| 407 |
+
from backend.core.config import API_KEYS, settings
|
| 408 |
+
|
| 409 |
+
client: QwenClient = request.app.state.qwen_client
|
| 410 |
+
token = _get_token(request)
|
| 411 |
+
if API_KEYS:
|
| 412 |
+
if token != settings.ADMIN_KEY and token not in API_KEYS:
|
| 413 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 414 |
+
|
| 415 |
+
content_type = (request.headers.get("content-type") or "").lower()
|
| 416 |
+
raw_files: list[tuple[bytes, str, str]] = []
|
| 417 |
+
prompt = ""
|
| 418 |
+
model_name: str | None = None
|
| 419 |
+
n = 1
|
| 420 |
+
size = None
|
| 421 |
+
response_format = "b64_json"
|
| 422 |
+
|
| 423 |
+
if "multipart/form-data" in content_type or "application/x-www-form-urlencoded" in content_type:
|
| 424 |
+
form = await request.form()
|
| 425 |
+
prompt = str(form.get("prompt") or "").strip()
|
| 426 |
+
model_name = str(form.get("model") or "") or None
|
| 427 |
+
try:
|
| 428 |
+
n = min(max(int(form.get("n") or 1), 1), 4)
|
| 429 |
+
except Exception:
|
| 430 |
+
n = 1
|
| 431 |
+
size = str(form.get("size") or "").strip() or None
|
| 432 |
+
response_format = str(form.get("response_format") or "b64_json").lower()
|
| 433 |
+
|
| 434 |
+
# OpenAI SDK may send image / image[] / image[0]
|
| 435 |
+
candidates: list[Any] = []
|
| 436 |
+
for key in form.keys():
|
| 437 |
+
kl = key.lower()
|
| 438 |
+
if kl == "image" or kl.startswith("image[") or kl.startswith("image_") or kl in {"mask"}:
|
| 439 |
+
if kl == "mask":
|
| 440 |
+
continue
|
| 441 |
+
val = form.getlist(key) if hasattr(form, "getlist") else [form.get(key)]
|
| 442 |
+
candidates.extend(val)
|
| 443 |
+
# also single get
|
| 444 |
+
if not candidates and form.get("image") is not None:
|
| 445 |
+
candidates = [form.get("image")]
|
| 446 |
+
|
| 447 |
+
for item in candidates:
|
| 448 |
+
if item is None:
|
| 449 |
+
continue
|
| 450 |
+
if hasattr(item, "read"):
|
| 451 |
+
raw = await item.read()
|
| 452 |
+
filename = getattr(item, "filename", None) or "ref.png"
|
| 453 |
+
ctype = getattr(item, "content_type", None) or mimetypes.guess_type(filename)[0] or "image/png"
|
| 454 |
+
if raw:
|
| 455 |
+
raw_files.append((raw, ctype, os.path.basename(filename) or "ref.png"))
|
| 456 |
+
elif isinstance(item, (bytes, bytearray)):
|
| 457 |
+
raw_files.append((bytes(item), "image/png", "ref.png"))
|
| 458 |
+
elif isinstance(item, str) and item.strip():
|
| 459 |
+
# data url or path unlikely in multipart text; skip
|
| 460 |
+
pass
|
| 461 |
+
else:
|
| 462 |
+
try:
|
| 463 |
+
body = await request.json()
|
| 464 |
+
except Exception:
|
| 465 |
+
raise HTTPException(status_code=400, detail="Invalid JSON body; use multipart or JSON")
|
| 466 |
+
prompt = str(body.get("prompt") or "").strip()
|
| 467 |
+
model_name = body.get("model")
|
| 468 |
+
try:
|
| 469 |
+
n = min(max(int(body.get("n", 1)), 1), 4)
|
| 470 |
+
except Exception:
|
| 471 |
+
n = 1
|
| 472 |
+
size = str(body.get("size") or "").strip() or None
|
| 473 |
+
response_format = str(body.get("response_format") or "b64_json").lower()
|
| 474 |
+
|
| 475 |
+
def _add_str_image(val: str):
|
| 476 |
+
v = val.strip()
|
| 477 |
+
if not v:
|
| 478 |
+
return
|
| 479 |
+
if v.startswith("data:"):
|
| 480 |
+
header, b64 = v.split(",", 1)
|
| 481 |
+
ctype = "image/png"
|
| 482 |
+
if ";" in header:
|
| 483 |
+
ctype = header[5:].split(";")[0] or ctype
|
| 484 |
+
raw = base64.b64decode(b64)
|
| 485 |
+
ext = mimetypes.guess_extension(ctype) or ".png"
|
| 486 |
+
raw_files.append((raw, ctype, f"ref{ext}"))
|
| 487 |
+
elif v.startswith("http://") or v.startswith("https://"):
|
| 488 |
+
import urllib.request
|
| 489 |
+
|
| 490 |
+
req = urllib.request.Request(v, headers={"User-Agent": "qwen2api-i2i/1.0"})
|
| 491 |
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
| 492 |
+
raw = resp.read()
|
| 493 |
+
ctype = resp.headers.get("Content-Type") or "image/png"
|
| 494 |
+
ext = mimetypes.guess_extension(ctype.split(";")[0].strip()) or ".png"
|
| 495 |
+
raw_files.append((raw, ctype.split(";")[0].strip(), f"ref{ext}"))
|
| 496 |
+
elif os.path.exists(v):
|
| 497 |
+
raw = open(v, "rb").read()
|
| 498 |
+
ctype = mimetypes.guess_type(v)[0] or "image/png"
|
| 499 |
+
raw_files.append((raw, ctype, os.path.basename(v) or "ref.png"))
|
| 500 |
+
|
| 501 |
+
for key in ("image", "image_url", "reference_image", "ref_image"):
|
| 502 |
+
val = body.get(key)
|
| 503 |
+
if isinstance(val, str):
|
| 504 |
+
_add_str_image(val)
|
| 505 |
+
for key in ("images", "image_urls", "reference_images"):
|
| 506 |
+
val = body.get(key)
|
| 507 |
+
if isinstance(val, list):
|
| 508 |
+
for item in val:
|
| 509 |
+
if isinstance(item, str):
|
| 510 |
+
_add_str_image(item)
|
| 511 |
+
elif isinstance(item, dict):
|
| 512 |
+
u = item.get("url") or item.get("image_url") or item.get("b64_json") or item.get("data")
|
| 513 |
+
if isinstance(u, str):
|
| 514 |
+
if item.get("b64_json") and not u.startswith("data:"):
|
| 515 |
+
_add_str_image("data:image/png;base64," + u)
|
| 516 |
+
else:
|
| 517 |
+
_add_str_image(u)
|
| 518 |
+
|
| 519 |
+
if not prompt:
|
| 520 |
+
raise HTTPException(status_code=400, detail="prompt is required")
|
| 521 |
+
if not raw_files:
|
| 522 |
+
raise HTTPException(status_code=400, detail="image is required for edits/i2i")
|
| 523 |
+
|
| 524 |
+
model = _resolve_image_model(model_name)
|
| 525 |
+
log.info("[I2I] model=%s n=%s refs=%s prompt=%r", model, n, len(raw_files), prompt[:100])
|
| 526 |
+
|
| 527 |
+
acc = None
|
| 528 |
+
chat_id = None
|
| 529 |
+
try:
|
| 530 |
+
if client.account_pool is None:
|
| 531 |
+
raise HTTPException(status_code=500, detail="No upstream account pool configured")
|
| 532 |
+
acc = await client.account_pool.acquire_wait(timeout=30)
|
| 533 |
+
if acc is None:
|
| 534 |
+
raise HTTPException(status_code=503, detail="No available upstream accounts")
|
| 535 |
+
|
| 536 |
+
files = await _upload_i2i_refs(client, acc, raw_files)
|
| 537 |
+
if not files or not any(f.get("url") for f in files):
|
| 538 |
+
raise HTTPException(status_code=500, detail="Failed to upload reference image(s) to upstream")
|
| 539 |
+
|
| 540 |
+
prompt_text = _build_i2i_prompt(prompt)
|
| 541 |
+
# 网页侧图生图:带 vision 参考图的 t2i / t2t 会话
|
| 542 |
+
chat_type = "t2i"
|
| 543 |
+
try:
|
| 544 |
+
chat_id = await client.create_chat(acc.token, model, chat_type=chat_type)
|
| 545 |
+
except Exception as e:
|
| 546 |
+
log.warning("[I2I] create_chat t2i failed (%s), fallback t2t", e)
|
| 547 |
+
chat_type = "t2t"
|
| 548 |
+
chat_id = await client.create_chat(acc.token, model, chat_type=chat_type)
|
| 549 |
+
|
| 550 |
+
log.info("[I2I] chat_id=%s account=%s chat_type=%s files=%s", chat_id, getattr(acc, "email", ""), chat_type, len(files))
|
| 551 |
+
|
| 552 |
+
completion = await client.complete_once(
|
| 553 |
+
acc.token,
|
| 554 |
+
chat_id,
|
| 555 |
+
model,
|
| 556 |
+
prompt_text,
|
| 557 |
+
has_custom_tools=False,
|
| 558 |
+
files=files,
|
| 559 |
+
chat_type=chat_type,
|
| 560 |
+
size=size,
|
| 561 |
+
)
|
| 562 |
+
|
| 563 |
+
search_payload: list[Any] = [completion]
|
| 564 |
+
try:
|
| 565 |
+
chat_detail = await client.get_chat(acc.token, chat_id)
|
| 566 |
+
search_payload.append(chat_detail)
|
| 567 |
+
except Exception as chat_error:
|
| 568 |
+
log.warning("[I2I] get_chat failed: %s", chat_error)
|
| 569 |
+
|
| 570 |
+
task_ids = _extract_task_ids(search_payload)
|
| 571 |
+
if task_ids:
|
| 572 |
+
log.info("[I2I] task IDs: %s", task_ids)
|
| 573 |
+
task_result = await _poll_image_task(client, acc.token, task_ids[0])
|
| 574 |
+
search_payload.append(task_result)
|
| 575 |
+
|
| 576 |
+
image_urls = _extract_image_urls(search_payload)
|
| 577 |
+
log.info("[I2I] extracted %s image URLs: %s", len(image_urls), image_urls[:5])
|
| 578 |
+
if not image_urls:
|
| 579 |
+
raise HTTPException(status_code=500, detail="Image edit succeeded but no URL found")
|
| 580 |
+
|
| 581 |
+
return await _pack_image_response(
|
| 582 |
+
image_urls,
|
| 583 |
+
prompt=prompt,
|
| 584 |
+
n=n,
|
| 585 |
+
response_format=response_format,
|
| 586 |
+
)
|
| 587 |
+
except HTTPException:
|
| 588 |
+
raise
|
| 589 |
+
except Exception as e:
|
| 590 |
+
log.error("[I2I] edit failed: %s", e)
|
| 591 |
+
raise HTTPException(status_code=500, detail=str(e))
|
| 592 |
+
finally:
|
| 593 |
+
if acc is not None:
|
| 594 |
+
try:
|
| 595 |
+
client.account_pool.release(acc)
|
| 596 |
+
except Exception:
|
| 597 |
+
pass
|
| 598 |
+
if chat_id:
|
| 599 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
backend/api/models.py
ADDED
|
@@ -0,0 +1,59 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 2 |
+
from fastapi.responses import JSONResponse
|
| 3 |
+
|
| 4 |
+
from backend.core.config import MODEL_MAP, resolve_model
|
| 5 |
+
from backend.services.auth_quota import resolve_auth_context
|
| 6 |
+
from backend.services.qwen_client import QwenClient
|
| 7 |
+
|
| 8 |
+
router = APIRouter()
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
def _build_model_list_payload() -> dict:
|
| 12 |
+
seen: set[str] = set()
|
| 13 |
+
data: list[dict] = []
|
| 14 |
+
for model_id in MODEL_MAP:
|
| 15 |
+
if model_id in seen:
|
| 16 |
+
continue
|
| 17 |
+
seen.add(model_id)
|
| 18 |
+
data.append({"id": model_id, "object": "model", "owned_by": "qwen2api"})
|
| 19 |
+
return {"object": "list", "data": data}
|
| 20 |
+
|
| 21 |
+
|
| 22 |
+
@router.get("/v1/models")
|
| 23 |
+
async def list_models(request: Request):
|
| 24 |
+
app = request.app
|
| 25 |
+
users_db = app.state.users_db
|
| 26 |
+
client: QwenClient = app.state.qwen_client
|
| 27 |
+
|
| 28 |
+
# 鉴权(只校验客户端 API KEY,不把它当 Qwen token 用)
|
| 29 |
+
await resolve_auth_context(request, users_db)
|
| 30 |
+
|
| 31 |
+
# 从账号池拿合法 Qwen token 调上游 /api/models,带 5min 缓存
|
| 32 |
+
upstream_models = await client.list_models_from_pool()
|
| 33 |
+
|
| 34 |
+
if upstream_models:
|
| 35 |
+
data = []
|
| 36 |
+
for item in upstream_models:
|
| 37 |
+
if not isinstance(item, dict):
|
| 38 |
+
continue
|
| 39 |
+
model_id = item.get("id") or item.get("model") or item.get("name")
|
| 40 |
+
if not model_id:
|
| 41 |
+
continue
|
| 42 |
+
data.append({
|
| 43 |
+
"id": model_id,
|
| 44 |
+
"object": "model",
|
| 45 |
+
"owned_by": item.get("owned_by", "qwen"),
|
| 46 |
+
"created": item.get("created_at") or 0,
|
| 47 |
+
})
|
| 48 |
+
return JSONResponse({"object": "list", "data": data})
|
| 49 |
+
|
| 50 |
+
# 上游不可用时才回退到静态 MODEL_MAP(包含 gpt-4o/claude 等别名)
|
| 51 |
+
return JSONResponse(_build_model_list_payload())
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@router.get("/v1/models/{model_id}")
|
| 55 |
+
async def get_model(model_id: str):
|
| 56 |
+
resolved = resolve_model(model_id)
|
| 57 |
+
if resolved == model_id and model_id not in MODEL_MAP:
|
| 58 |
+
raise HTTPException(status_code=404, detail={"error": {"message": f"Model '{model_id}' not found", "type": "invalid_request_error"}})
|
| 59 |
+
return JSONResponse({"id": model_id, "object": "model", "owned_by": "qwen2api", "resolved_model": resolved})
|
backend/api/probes.py
ADDED
|
@@ -0,0 +1,41 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, Request, Depends, HTTPException
|
| 2 |
+
from backend.api.admin import verify_admin
|
| 3 |
+
from backend.core.database import AsyncJsonDB
|
| 4 |
+
|
| 5 |
+
router = APIRouter()
|
| 6 |
+
|
| 7 |
+
|
| 8 |
+
@router.get("/healthz")
|
| 9 |
+
async def healthz():
|
| 10 |
+
return {"status": "ok"}
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@router.get("/readyz")
|
| 14 |
+
async def readyz(request: Request):
|
| 15 |
+
required_state = (
|
| 16 |
+
"accounts_db",
|
| 17 |
+
"users_db",
|
| 18 |
+
"captures_db",
|
| 19 |
+
"account_pool",
|
| 20 |
+
"qwen_client",
|
| 21 |
+
"file_store",
|
| 22 |
+
"session_affinity",
|
| 23 |
+
"upstream_file_cache",
|
| 24 |
+
)
|
| 25 |
+
missing = [name for name in required_state if not hasattr(request.app.state, name)]
|
| 26 |
+
if missing:
|
| 27 |
+
raise HTTPException(status_code=503, detail={"status": "not_ready", "missing": missing})
|
| 28 |
+
return {"status": "ready"}
|
| 29 |
+
|
| 30 |
+
|
| 31 |
+
@router.get("/admin/dev/captures", dependencies=[Depends(verify_admin)])
|
| 32 |
+
async def get_captures(request: Request):
|
| 33 |
+
db: AsyncJsonDB = request.app.state.captures_db
|
| 34 |
+
return {"captures": await db.get()}
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
@router.delete("/admin/dev/captures", dependencies=[Depends(verify_admin)])
|
| 38 |
+
async def clear_captures(request: Request):
|
| 39 |
+
db: AsyncJsonDB = request.app.state.captures_db
|
| 40 |
+
await db.save([])
|
| 41 |
+
return {"status": "cleared"}
|
backend/api/v1_chat.py
ADDED
|
@@ -0,0 +1,235 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 2 |
+
from fastapi.responses import JSONResponse, StreamingResponse
|
| 3 |
+
import json
|
| 4 |
+
import logging
|
| 5 |
+
import time
|
| 6 |
+
import uuid
|
| 7 |
+
from typing import Any, Awaitable, Callable
|
| 8 |
+
from backend.adapter.standard_request import StandardRequest
|
| 9 |
+
from backend.core.config import settings
|
| 10 |
+
from backend.core.request_logging import new_request_id, request_context, update_request_context
|
| 11 |
+
from backend.services.attachment_preprocessor import preprocess_attachments
|
| 12 |
+
from backend.services.context_attachment_manager import prepare_context_attachments, derive_session_key
|
| 13 |
+
from backend.services.auth_quota import resolve_auth_context
|
| 14 |
+
from backend.services.completion_bridge import run_retryable_completion_bridge
|
| 15 |
+
from backend.services.openai_stream_translator import OpenAIStreamTranslator
|
| 16 |
+
from backend.services.prompt_builder import CLAUDE_CODE_OPENAI_PROFILE, OPENCLAW_OPENAI_PROFILE
|
| 17 |
+
from backend.services.response_formatters import build_openai_completion_payload
|
| 18 |
+
from backend.services.qwen_client import QwenClient
|
| 19 |
+
from backend.services.standard_request_builder import build_chat_standard_request
|
| 20 |
+
from backend.services.task_session import (
|
| 21 |
+
build_openai_assistant_history_message,
|
| 22 |
+
clear_invalidated_session_chat,
|
| 23 |
+
log_session_plan_reuse_cancelled,
|
| 24 |
+
persist_session_turn,
|
| 25 |
+
plan_persistent_session_turn,
|
| 26 |
+
)
|
| 27 |
+
from backend.runtime.execution import RuntimeAttemptState, build_tool_directive, build_usage_delta_factory, request_max_attempts
|
| 28 |
+
|
| 29 |
+
log = logging.getLogger("qwen2api.chat")
|
| 30 |
+
router = APIRouter()
|
| 31 |
+
OpenAIDeltaHandler = Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]]
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
def _detect_openai_client_profile(request: Request, req_data: dict) -> str:
|
| 35 |
+
del req_data
|
| 36 |
+
if request.headers.get("x-anthropic-billing-header"):
|
| 37 |
+
return CLAUDE_CODE_OPENAI_PROFILE
|
| 38 |
+
return OPENCLAW_OPENAI_PROFILE
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def _build_standard_request(req_data: dict, *, client_profile: str) -> StandardRequest:
|
| 42 |
+
standard_request = build_chat_standard_request(
|
| 43 |
+
req_data,
|
| 44 |
+
default_model="gpt-3.5-turbo",
|
| 45 |
+
surface="openai",
|
| 46 |
+
client_profile=client_profile,
|
| 47 |
+
)
|
| 48 |
+
log.info("[OAI] normalized tools=%s profile=%s", standard_request.tool_names, client_profile)
|
| 49 |
+
return standard_request
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
@router.post("/chat/completions")
|
| 53 |
+
@router.post("/v1/chat/completions")
|
| 54 |
+
async def chat_completions(request: Request):
|
| 55 |
+
app = request.app
|
| 56 |
+
users_db = app.state.users_db
|
| 57 |
+
client: QwenClient = app.state.qwen_client
|
| 58 |
+
|
| 59 |
+
auth = await resolve_auth_context(request, users_db)
|
| 60 |
+
token = auth.token
|
| 61 |
+
|
| 62 |
+
try:
|
| 63 |
+
req_data = await request.json()
|
| 64 |
+
except Exception:
|
| 65 |
+
raise HTTPException(400, {"error": {"message": "Invalid JSON body", "type": "invalid_request_error"}})
|
| 66 |
+
|
| 67 |
+
client_profile = _detect_openai_client_profile(request, req_data)
|
| 68 |
+
session_key = derive_session_key("openai", token, req_data)
|
| 69 |
+
original_history_messages = req_data.get("messages", [])
|
| 70 |
+
file_store = getattr(app.state, "file_store", None)
|
| 71 |
+
preprocessed = None
|
| 72 |
+
if file_store is not None:
|
| 73 |
+
preprocessed = await preprocess_attachments(req_data, file_store, owner_token=token)
|
| 74 |
+
req_data = preprocessed.payload
|
| 75 |
+
context_prepared = await prepare_context_attachments(app=app, payload=req_data, surface="openai", auth_token=token, client_profile=client_profile, existing_attachments=(preprocessed.attachments if preprocessed is not None else None))
|
| 76 |
+
req_data = context_prepared["payload"]
|
| 77 |
+
standard_request = _build_standard_request(req_data, client_profile=client_profile)
|
| 78 |
+
if preprocessed is not None:
|
| 79 |
+
standard_request.attachments = preprocessed.attachments
|
| 80 |
+
standard_request.uploaded_file_ids = preprocessed.uploaded_file_ids
|
| 81 |
+
standard_request.upstream_files = context_prepared["upstream_files"]
|
| 82 |
+
standard_request.session_key = context_prepared["session_key"]
|
| 83 |
+
standard_request.context_mode = context_prepared["context_mode"]
|
| 84 |
+
standard_request.bound_account_email = context_prepared["bound_account_email"]
|
| 85 |
+
standard_request.bound_account = context_prepared["bound_account"]
|
| 86 |
+
|
| 87 |
+
session_plan = await plan_persistent_session_turn(app=app, request=standard_request, payload=req_data, surface="openai")
|
| 88 |
+
if session_plan.enabled:
|
| 89 |
+
standard_request.persistent_session = True
|
| 90 |
+
standard_request.full_prompt = session_plan.full_prompt
|
| 91 |
+
standard_request.prompt = session_plan.prompt
|
| 92 |
+
standard_request.session_message_hashes = session_plan.current_hashes
|
| 93 |
+
standard_request.upstream_chat_id = session_plan.existing_chat_id if session_plan.reuse_chat else None
|
| 94 |
+
if standard_request.bound_account is None and session_plan.account_email:
|
| 95 |
+
standard_request.bound_account = await app.state.account_pool.acquire_wait_preferred(session_plan.account_email, timeout=60)
|
| 96 |
+
if standard_request.bound_account is not None:
|
| 97 |
+
standard_request.bound_account_email = standard_request.bound_account.email
|
| 98 |
+
elif standard_request.bound_account is not None and not standard_request.bound_account_email:
|
| 99 |
+
standard_request.bound_account_email = standard_request.bound_account.email
|
| 100 |
+
if standard_request.upstream_chat_id and standard_request.bound_account is None:
|
| 101 |
+
log_session_plan_reuse_cancelled(
|
| 102 |
+
request=standard_request,
|
| 103 |
+
planned_chat_id=session_plan.existing_chat_id,
|
| 104 |
+
reason="missing_bound_account",
|
| 105 |
+
)
|
| 106 |
+
standard_request.upstream_chat_id = None
|
| 107 |
+
standard_request.prompt = standard_request.full_prompt or standard_request.prompt
|
| 108 |
+
|
| 109 |
+
model_name = standard_request.response_model
|
| 110 |
+
qwen_model = standard_request.resolved_model
|
| 111 |
+
prompt = standard_request.prompt
|
| 112 |
+
tools = standard_request.tools
|
| 113 |
+
history_messages = original_history_messages
|
| 114 |
+
|
| 115 |
+
completion_id = f"chatcmpl-{uuid.uuid4().hex[:12]}"
|
| 116 |
+
created = int(time.time())
|
| 117 |
+
|
| 118 |
+
with request_context(req_id=new_request_id(), surface="openai", requested_model=model_name, resolved_model=qwen_model):
|
| 119 |
+
log.info(
|
| 120 |
+
"[OAI] model=%s stream=%s tool_enabled=%s profile=%s tools=%s prompt_len=%s prompt_tail=%r",
|
| 121 |
+
qwen_model,
|
| 122 |
+
standard_request.stream,
|
| 123 |
+
standard_request.tool_enabled,
|
| 124 |
+
standard_request.client_profile,
|
| 125 |
+
[t.get('name') for t in tools],
|
| 126 |
+
len(prompt),
|
| 127 |
+
prompt[-500:],
|
| 128 |
+
)
|
| 129 |
+
|
| 130 |
+
if standard_request.stream:
|
| 131 |
+
async def generate():
|
| 132 |
+
async with app.state.session_locks.hold(session_key):
|
| 133 |
+
try:
|
| 134 |
+
update_request_context(stream_attempt=1)
|
| 135 |
+
translator = OpenAIStreamTranslator(
|
| 136 |
+
completion_id=completion_id,
|
| 137 |
+
created=created,
|
| 138 |
+
model_name=model_name,
|
| 139 |
+
client_profile=standard_request.client_profile,
|
| 140 |
+
build_final_directive=lambda answer_text: build_tool_directive(
|
| 141 |
+
standard_request,
|
| 142 |
+
RuntimeAttemptState(answer_text=answer_text),
|
| 143 |
+
),
|
| 144 |
+
allowed_tool_names=standard_request.tool_names,
|
| 145 |
+
)
|
| 146 |
+
|
| 147 |
+
async def on_delta(evt: dict[str, Any], text_chunk: str | None, tool_calls: list[dict[str, Any]] | None) -> None:
|
| 148 |
+
translator.on_delta(evt, text_chunk, tool_calls)
|
| 149 |
+
|
| 150 |
+
result = await run_retryable_completion_bridge(
|
| 151 |
+
client=client,
|
| 152 |
+
standard_request=standard_request,
|
| 153 |
+
prompt=prompt,
|
| 154 |
+
users_db=users_db,
|
| 155 |
+
token=token,
|
| 156 |
+
history_messages=history_messages,
|
| 157 |
+
max_attempts=request_max_attempts(standard_request),
|
| 158 |
+
usage_delta_factory=build_usage_delta_factory(prompt),
|
| 159 |
+
allow_after_visible_output=True,
|
| 160 |
+
capture_events=False,
|
| 161 |
+
on_delta=on_delta,
|
| 162 |
+
)
|
| 163 |
+
execution = result.execution
|
| 164 |
+
directive = result.directive or build_tool_directive(standard_request, execution.state)
|
| 165 |
+
assistant_message = build_openai_assistant_history_message(
|
| 166 |
+
execution=execution,
|
| 167 |
+
request=standard_request,
|
| 168 |
+
directive=directive,
|
| 169 |
+
)
|
| 170 |
+
await persist_session_turn(
|
| 171 |
+
app=app,
|
| 172 |
+
request=standard_request,
|
| 173 |
+
surface="openai",
|
| 174 |
+
execution=execution,
|
| 175 |
+
assistant_message=assistant_message,
|
| 176 |
+
)
|
| 177 |
+
final_finish_reason = "tool_calls" if directive.stop_reason == "tool_use" else execution.state.finish_reason
|
| 178 |
+
for chunk in translator.finalize(final_finish_reason):
|
| 179 |
+
yield chunk
|
| 180 |
+
return
|
| 181 |
+
except HTTPException as he:
|
| 182 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 183 |
+
yield f"data: {json.dumps({'error': he.detail})}\n\n"
|
| 184 |
+
return
|
| 185 |
+
except Exception as e:
|
| 186 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 187 |
+
yield f"data: {json.dumps({'error': str(e)})}\n\n"
|
| 188 |
+
return
|
| 189 |
+
|
| 190 |
+
return StreamingResponse(
|
| 191 |
+
generate(),
|
| 192 |
+
media_type="text/event-stream",
|
| 193 |
+
headers={"Cache-Control": "no-cache", "X-Accel-Buffering": "no"},
|
| 194 |
+
)
|
| 195 |
+
|
| 196 |
+
try:
|
| 197 |
+
async with app.state.session_locks.hold(session_key):
|
| 198 |
+
update_request_context(stream_attempt=1)
|
| 199 |
+
result = await run_retryable_completion_bridge(
|
| 200 |
+
client=client,
|
| 201 |
+
standard_request=standard_request,
|
| 202 |
+
prompt=prompt,
|
| 203 |
+
users_db=users_db,
|
| 204 |
+
token=token,
|
| 205 |
+
history_messages=history_messages,
|
| 206 |
+
max_attempts=request_max_attempts(standard_request),
|
| 207 |
+
usage_delta_factory=build_usage_delta_factory(prompt),
|
| 208 |
+
allow_after_visible_output=True,
|
| 209 |
+
)
|
| 210 |
+
execution = result.execution
|
| 211 |
+
directive = result.directive or build_tool_directive(standard_request, execution.state)
|
| 212 |
+
assistant_message = build_openai_assistant_history_message(
|
| 213 |
+
execution=execution,
|
| 214 |
+
request=standard_request,
|
| 215 |
+
directive=directive,
|
| 216 |
+
)
|
| 217 |
+
await persist_session_turn(
|
| 218 |
+
app=app,
|
| 219 |
+
request=standard_request,
|
| 220 |
+
surface="openai",
|
| 221 |
+
execution=execution,
|
| 222 |
+
assistant_message=assistant_message,
|
| 223 |
+
)
|
| 224 |
+
|
| 225 |
+
return JSONResponse(build_openai_completion_payload(
|
| 226 |
+
completion_id=completion_id,
|
| 227 |
+
created=created,
|
| 228 |
+
model_name=model_name,
|
| 229 |
+
prompt=result.prompt,
|
| 230 |
+
execution=execution,
|
| 231 |
+
standard_request=standard_request,
|
| 232 |
+
))
|
| 233 |
+
except Exception as e:
|
| 234 |
+
await clear_invalidated_session_chat(app=app, request=standard_request)
|
| 235 |
+
raise HTTPException(status_code=500, detail=str(e))
|
backend/api/videos.py
ADDED
|
@@ -0,0 +1,652 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
import os
|
| 5 |
+
import re
|
| 6 |
+
import time
|
| 7 |
+
import uuid
|
| 8 |
+
from typing import Any
|
| 9 |
+
|
| 10 |
+
from fastapi import APIRouter, HTTPException, Request
|
| 11 |
+
from fastapi.responses import JSONResponse
|
| 12 |
+
|
| 13 |
+
from backend.services.qwen_client import QwenClient
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger("qwen2api.videos")
|
| 16 |
+
router = APIRouter()
|
| 17 |
+
|
| 18 |
+
DEFAULT_VIDEO_MODEL = "qwen3.6-plus"
|
| 19 |
+
VIDEO_BUSY_EMAILS: set[str] = set()
|
| 20 |
+
VIDEO_BUSY_LOCK = asyncio.Lock()
|
| 21 |
+
|
| 22 |
+
# Async task store for NewAPI/ArcReel polling protocol.
|
| 23 |
+
# ArcReel's newapi-video backend expects:
|
| 24 |
+
# POST /v1/video/generations -> {"task_id": "..."}
|
| 25 |
+
# GET /v1/video/generations/{task_id} -> {"status":"completed","url":"..."}
|
| 26 |
+
# The old sync path waited ~90s and exceeded ArcReel's 60s create timeout
|
| 27 |
+
# (create_ambiguous). Background jobs fix that.
|
| 28 |
+
VIDEO_TASKS: dict[str, dict[str, Any]] = {}
|
| 29 |
+
VIDEO_TASKS_LOCK = asyncio.Lock()
|
| 30 |
+
VIDEO_TASK_TTL_SECONDS = 3600
|
| 31 |
+
|
| 32 |
+
VIDEO_MODEL_MAP = {
|
| 33 |
+
"sora": "qwen3.6-plus",
|
| 34 |
+
"sora-1.0-turbo": "qwen3.6-plus",
|
| 35 |
+
"qwen-video": "qwen3.6-plus",
|
| 36 |
+
"qwen-video-plus": "qwen3.6-plus",
|
| 37 |
+
"qwen3.6-plus": "qwen3.6-plus",
|
| 38 |
+
}
|
| 39 |
+
|
| 40 |
+
HTTP_URL_RE = re.compile(r"https?://[^\s\"'<>)]*", re.IGNORECASE)
|
| 41 |
+
VIDEO_EXT_RE = re.compile(r"\.(?:mp4|webm|mov|m3u8|m4v)(?:[?#]|$)", re.IGNORECASE)
|
| 42 |
+
IMAGE_EXT_RE = re.compile(r"\.(?:jpg|jpeg|png|webp|gif|svg)(?:[?#]|$)", re.IGNORECASE)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def _resolve_video_model(requested: str | None) -> str:
|
| 46 |
+
if not requested:
|
| 47 |
+
return DEFAULT_VIDEO_MODEL
|
| 48 |
+
return VIDEO_MODEL_MAP.get(requested, DEFAULT_VIDEO_MODEL)
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
def _get_token(request: Request) -> str:
|
| 52 |
+
auth = request.headers.get("Authorization", "")
|
| 53 |
+
if auth.startswith("Bearer "):
|
| 54 |
+
return auth[7:].strip()
|
| 55 |
+
return request.headers.get("x-api-key", "").strip()
|
| 56 |
+
|
| 57 |
+
|
| 58 |
+
def _looks_like_video_url(url: str, key_hint: str = "") -> bool:
|
| 59 |
+
lowered = url.lower().rstrip(".,;)\"'>")
|
| 60 |
+
if IMAGE_EXT_RE.search(lowered):
|
| 61 |
+
return False
|
| 62 |
+
if VIDEO_EXT_RE.search(lowered):
|
| 63 |
+
return True
|
| 64 |
+
hint = key_hint.lower()
|
| 65 |
+
if any(token in hint for token in ("video", "media", "download", "play")):
|
| 66 |
+
return True
|
| 67 |
+
return any(token in lowered for token in ("/video", "video_", "video-", "/videos", "m3u8"))
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def _extract_video_urls(value: Any, key_hint: str = "") -> list[str]:
|
| 71 |
+
urls: list[str] = []
|
| 72 |
+
|
| 73 |
+
if value is None:
|
| 74 |
+
return urls
|
| 75 |
+
|
| 76 |
+
if isinstance(value, str):
|
| 77 |
+
for raw_url in HTTP_URL_RE.findall(value):
|
| 78 |
+
url = raw_url.rstrip(".,;)\"'>")
|
| 79 |
+
if _looks_like_video_url(url, key_hint):
|
| 80 |
+
urls.append(url)
|
| 81 |
+
return urls
|
| 82 |
+
|
| 83 |
+
if isinstance(value, list):
|
| 84 |
+
for item in value:
|
| 85 |
+
urls.extend(_extract_video_urls(item, key_hint))
|
| 86 |
+
return urls
|
| 87 |
+
|
| 88 |
+
if isinstance(value, dict):
|
| 89 |
+
for key, item in value.items():
|
| 90 |
+
next_hint = str(key)
|
| 91 |
+
urls.extend(_extract_video_urls(item, next_hint))
|
| 92 |
+
return urls
|
| 93 |
+
|
| 94 |
+
return urls
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
def _extract_task_ids(value: Any) -> list[str]:
|
| 98 |
+
task_ids: list[str] = []
|
| 99 |
+
|
| 100 |
+
if value is None:
|
| 101 |
+
return task_ids
|
| 102 |
+
|
| 103 |
+
if isinstance(value, list):
|
| 104 |
+
for item in value:
|
| 105 |
+
task_ids.extend(_extract_task_ids(item))
|
| 106 |
+
return task_ids
|
| 107 |
+
|
| 108 |
+
if isinstance(value, dict):
|
| 109 |
+
for key, item in value.items():
|
| 110 |
+
if key in {"task_id", "taskId"} and isinstance(item, str) and item.strip():
|
| 111 |
+
task_ids.append(item.strip())
|
| 112 |
+
else:
|
| 113 |
+
task_ids.extend(_extract_task_ids(item))
|
| 114 |
+
|
| 115 |
+
return task_ids
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
def _dedupe(values: list[str]) -> list[str]:
|
| 119 |
+
seen: set[str] = set()
|
| 120 |
+
result: list[str] = []
|
| 121 |
+
for value in values:
|
| 122 |
+
if value not in seen:
|
| 123 |
+
seen.add(value)
|
| 124 |
+
result.append(value)
|
| 125 |
+
return result
|
| 126 |
+
|
| 127 |
+
|
| 128 |
+
def _build_video_prompt(prompt: str, size: str | None) -> str:
|
| 129 |
+
return prompt
|
| 130 |
+
|
| 131 |
+
|
| 132 |
+
def _decode_image_input(image_value: str) -> tuple[bytes, str, str]:
|
| 133 |
+
"""Return (raw_bytes, content_type, filename) from data-url or http(s) url."""
|
| 134 |
+
import base64
|
| 135 |
+
import mimetypes
|
| 136 |
+
import urllib.request
|
| 137 |
+
|
| 138 |
+
value = (image_value or "").strip()
|
| 139 |
+
if not value:
|
| 140 |
+
raise HTTPException(status_code=400, detail="empty image")
|
| 141 |
+
|
| 142 |
+
if value.startswith("data:"):
|
| 143 |
+
header, b64 = value.split(",", 1)
|
| 144 |
+
content_type = "image/png"
|
| 145 |
+
if ";" in header:
|
| 146 |
+
content_type = header[5:].split(";")[0] or content_type
|
| 147 |
+
raw = base64.b64decode(b64)
|
| 148 |
+
ext = mimetypes.guess_extension(content_type) or ".png"
|
| 149 |
+
return raw, content_type, f"ref{ext}"
|
| 150 |
+
|
| 151 |
+
if value.startswith("http://") or value.startswith("https://"):
|
| 152 |
+
req = urllib.request.Request(value, headers={"User-Agent": "qwen2api-video/1.0"})
|
| 153 |
+
with urllib.request.urlopen(req, timeout=60) as resp:
|
| 154 |
+
raw = resp.read()
|
| 155 |
+
content_type = resp.headers.get("Content-Type") or "image/png"
|
| 156 |
+
ext = mimetypes.guess_extension(content_type.split(";")[0].strip()) or ".png"
|
| 157 |
+
return raw, content_type.split(";")[0].strip(), f"ref{ext}"
|
| 158 |
+
|
| 159 |
+
# local path
|
| 160 |
+
if os.path.exists(value):
|
| 161 |
+
raw = open(value, "rb").read()
|
| 162 |
+
content_type = mimetypes.guess_type(value)[0] or "image/png"
|
| 163 |
+
return raw, content_type, os.path.basename(value) or "ref.png"
|
| 164 |
+
|
| 165 |
+
raise HTTPException(status_code=400, detail="image must be data-url, http(s) url, or local path")
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
async def _upload_reference_images(client: QwenClient, acc: Any, images: list[str]) -> list[dict]:
|
| 169 |
+
"""Upload one or more reference images and return remote file refs for complete_once(files=...)."""
|
| 170 |
+
if not images:
|
| 171 |
+
return []
|
| 172 |
+
|
| 173 |
+
from backend.core.config import settings
|
| 174 |
+
from backend.services.upstream_file_uploader import UpstreamFileUploader
|
| 175 |
+
|
| 176 |
+
uploader = UpstreamFileUploader(client, settings)
|
| 177 |
+
files: list[dict] = []
|
| 178 |
+
tmp_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(__file__))), "logs", "video_refs")
|
| 179 |
+
os.makedirs(tmp_dir, exist_ok=True)
|
| 180 |
+
|
| 181 |
+
for idx, image_value in enumerate(images[:4]):
|
| 182 |
+
raw, content_type, filename = _decode_image_input(image_value)
|
| 183 |
+
local_path = os.path.join(tmp_dir, f"{int(time.time())}_{idx}_{filename}")
|
| 184 |
+
with open(local_path, "wb") as f:
|
| 185 |
+
f.write(raw)
|
| 186 |
+
meta = {
|
| 187 |
+
"filename": filename,
|
| 188 |
+
"path": local_path,
|
| 189 |
+
"content_type": content_type,
|
| 190 |
+
"size": len(raw),
|
| 191 |
+
}
|
| 192 |
+
remote = await uploader.upload_local_file(acc, meta)
|
| 193 |
+
ref = remote.get("remote_ref")
|
| 194 |
+
put_url = ""
|
| 195 |
+
if isinstance(ref, dict):
|
| 196 |
+
put_url = str(ref.get("url") or "")
|
| 197 |
+
if not put_url:
|
| 198 |
+
# fallback construct from uploader fields if present
|
| 199 |
+
put_url = str(remote.get("url") or "")
|
| 200 |
+
|
| 201 |
+
# Frontend real i2v file object (from chat.qwen.ai frontend_main.js):
|
| 202 |
+
# {type:"image", name, file_type, showType:"image", status:"uploaded",
|
| 203 |
+
# file_class:"vision", url}
|
| 204 |
+
# When VideoGeneration + image file is present, frontend auto-switches to i2v.
|
| 205 |
+
vision_ref = {
|
| 206 |
+
"type": "image",
|
| 207 |
+
"name": filename,
|
| 208 |
+
"file_type": content_type if content_type.startswith("image/") else "image/png",
|
| 209 |
+
"showType": "image",
|
| 210 |
+
"status": "uploaded",
|
| 211 |
+
"file_class": "vision",
|
| 212 |
+
"url": put_url,
|
| 213 |
+
}
|
| 214 |
+
# Keep upstream file id if available (some servers use it).
|
| 215 |
+
if isinstance(ref, dict):
|
| 216 |
+
if ref.get("id"):
|
| 217 |
+
vision_ref["id"] = ref.get("id")
|
| 218 |
+
if isinstance(ref.get("file"), dict) and ref["file"].get("id"):
|
| 219 |
+
vision_ref["file"] = ref["file"]
|
| 220 |
+
# merge non-conflicting extras
|
| 221 |
+
for k in ("itemId", "uploadTaskId", "size", "greenNet", "progress", "error", "collection_name"):
|
| 222 |
+
if k in ref and k not in vision_ref:
|
| 223 |
+
vision_ref[k] = ref[k]
|
| 224 |
+
|
| 225 |
+
if not vision_ref.get("url"):
|
| 226 |
+
log.warning("[T2V] upload missing url, remote=%s", remote)
|
| 227 |
+
files.append(vision_ref)
|
| 228 |
+
log.info(
|
| 229 |
+
"[T2V] uploaded reference image file_id=%s name=%s url=%s type=%s class=%s",
|
| 230 |
+
remote.get("remote_file_id"),
|
| 231 |
+
filename,
|
| 232 |
+
(vision_ref.get("url") or "")[:120],
|
| 233 |
+
vision_ref.get("type"),
|
| 234 |
+
vision_ref.get("file_class"),
|
| 235 |
+
)
|
| 236 |
+
return files
|
| 237 |
+
|
| 238 |
+
|
| 239 |
+
def _collect_images_from_body(body: dict) -> list[str]:
|
| 240 |
+
images: list[str] = []
|
| 241 |
+
for key in ("image", "image_url", "reference_image", "ref_image"):
|
| 242 |
+
val = body.get(key)
|
| 243 |
+
if isinstance(val, str) and val.strip():
|
| 244 |
+
images.append(val.strip())
|
| 245 |
+
for key in ("images", "image_urls", "reference_images"):
|
| 246 |
+
val = body.get(key)
|
| 247 |
+
if isinstance(val, list):
|
| 248 |
+
for item in val:
|
| 249 |
+
if isinstance(item, str) and item.strip():
|
| 250 |
+
images.append(item.strip())
|
| 251 |
+
elif isinstance(item, dict):
|
| 252 |
+
u = item.get("url") or item.get("image_url") or item.get("data")
|
| 253 |
+
if isinstance(u, str) and u.strip():
|
| 254 |
+
images.append(u.strip())
|
| 255 |
+
# de-dupe keep order
|
| 256 |
+
seen: set[str] = set()
|
| 257 |
+
out: list[str] = []
|
| 258 |
+
for u in images:
|
| 259 |
+
if u not in seen:
|
| 260 |
+
seen.add(u)
|
| 261 |
+
out.append(u)
|
| 262 |
+
return out
|
| 263 |
+
|
| 264 |
+
|
| 265 |
+
def _video_account_wait_seconds() -> int:
|
| 266 |
+
try:
|
| 267 |
+
return max(30, int(os.getenv("QWEN_VIDEO_ACCOUNT_WAIT_SECONDS", "900")))
|
| 268 |
+
except Exception:
|
| 269 |
+
return 900
|
| 270 |
+
|
| 271 |
+
|
| 272 |
+
async def _acquire_video_account(client: QwenClient):
|
| 273 |
+
if client.account_pool is None:
|
| 274 |
+
raise HTTPException(status_code=500, detail="No upstream account pool configured")
|
| 275 |
+
|
| 276 |
+
deadline = time.monotonic() + _video_account_wait_seconds()
|
| 277 |
+
|
| 278 |
+
while time.monotonic() < deadline:
|
| 279 |
+
async with VIDEO_BUSY_LOCK:
|
| 280 |
+
exclude = set(VIDEO_BUSY_EMAILS)
|
| 281 |
+
|
| 282 |
+
remaining = max(1, deadline - time.monotonic())
|
| 283 |
+
acc = await client.account_pool.acquire_wait(timeout=min(10, remaining), exclude=exclude)
|
| 284 |
+
if acc is None:
|
| 285 |
+
await asyncio.sleep(2)
|
| 286 |
+
continue
|
| 287 |
+
|
| 288 |
+
email = getattr(acc, "email", "") or ""
|
| 289 |
+
async with VIDEO_BUSY_LOCK:
|
| 290 |
+
if email not in VIDEO_BUSY_EMAILS:
|
| 291 |
+
VIDEO_BUSY_EMAILS.add(email)
|
| 292 |
+
return acc
|
| 293 |
+
|
| 294 |
+
client.account_pool.release(acc)
|
| 295 |
+
await asyncio.sleep(1)
|
| 296 |
+
|
| 297 |
+
raise HTTPException(status_code=503, detail="No available upstream video accounts")
|
| 298 |
+
|
| 299 |
+
|
| 300 |
+
async def _release_video_account(client: QwenClient, acc: Any):
|
| 301 |
+
email = getattr(acc, "email", "") or ""
|
| 302 |
+
async with VIDEO_BUSY_LOCK:
|
| 303 |
+
VIDEO_BUSY_EMAILS.discard(email)
|
| 304 |
+
client.account_pool.release(acc)
|
| 305 |
+
|
| 306 |
+
|
| 307 |
+
async def _poll_video_task(client: QwenClient, token: str, task_id: str, *, timeout_seconds: int = 420) -> dict:
|
| 308 |
+
started_at = time.monotonic()
|
| 309 |
+
last_status: dict = {}
|
| 310 |
+
|
| 311 |
+
while time.monotonic() - started_at < timeout_seconds:
|
| 312 |
+
task_status = await client.get_task_status(token, task_id)
|
| 313 |
+
last_status = task_status
|
| 314 |
+
data = task_status.get("data") if isinstance(task_status, dict) else None
|
| 315 |
+
if not isinstance(data, dict) and isinstance(task_status, dict):
|
| 316 |
+
data = task_status
|
| 317 |
+
if not isinstance(data, dict):
|
| 318 |
+
await asyncio.sleep(5)
|
| 319 |
+
continue
|
| 320 |
+
|
| 321 |
+
state = str(data.get("task_status") or data.get("status") or "").lower()
|
| 322 |
+
log.info("[T2V] task_id=%s status=%s", task_id, state)
|
| 323 |
+
if state == "success":
|
| 324 |
+
return task_status
|
| 325 |
+
if state not in {"running", "pending", "queued", "created", "processing", ""}:
|
| 326 |
+
raise HTTPException(status_code=500, detail={"message": "Video task failed", "task_status": data})
|
| 327 |
+
|
| 328 |
+
await asyncio.sleep(10)
|
| 329 |
+
|
| 330 |
+
raise HTTPException(status_code=504, detail={"message": "Video task timed out", "task_id": task_id, "last_status": last_status})
|
| 331 |
+
|
| 332 |
+
|
| 333 |
+
def _normalize_size(body: dict) -> str | None:
|
| 334 |
+
"""Accept size=1280*720 or ArcReel/newapi width+height."""
|
| 335 |
+
size = str(body.get("size", "")).strip() or None
|
| 336 |
+
if size:
|
| 337 |
+
return size
|
| 338 |
+
width = body.get("width")
|
| 339 |
+
height = body.get("height")
|
| 340 |
+
try:
|
| 341 |
+
if width and height:
|
| 342 |
+
return f"{int(width)}*{int(height)}"
|
| 343 |
+
except Exception:
|
| 344 |
+
pass
|
| 345 |
+
return None
|
| 346 |
+
|
| 347 |
+
|
| 348 |
+
async def _purge_old_video_tasks() -> None:
|
| 349 |
+
now = time.time()
|
| 350 |
+
async with VIDEO_TASKS_LOCK:
|
| 351 |
+
dead = [tid for tid, t in VIDEO_TASKS.items() if now - float(t.get("created_at", now)) > VIDEO_TASK_TTL_SECONDS]
|
| 352 |
+
for tid in dead:
|
| 353 |
+
VIDEO_TASKS.pop(tid, None)
|
| 354 |
+
|
| 355 |
+
|
| 356 |
+
async def _set_video_task(task_id: str, **fields: Any) -> None:
|
| 357 |
+
async with VIDEO_TASKS_LOCK:
|
| 358 |
+
cur = VIDEO_TASKS.get(task_id) or {"task_id": task_id, "created_at": time.time()}
|
| 359 |
+
cur.update(fields)
|
| 360 |
+
cur["updated_at"] = time.time()
|
| 361 |
+
VIDEO_TASKS[task_id] = cur
|
| 362 |
+
|
| 363 |
+
|
| 364 |
+
async def _get_video_task(task_id: str) -> dict[str, Any] | None:
|
| 365 |
+
async with VIDEO_TASKS_LOCK:
|
| 366 |
+
return dict(VIDEO_TASKS.get(task_id) or {}) or None
|
| 367 |
+
|
| 368 |
+
|
| 369 |
+
async def _run_video_job(app: Any, task_id: str, body: dict) -> None:
|
| 370 |
+
"""Background worker: full Qwen t2v/i2v pipeline, then update VIDEO_TASKS."""
|
| 371 |
+
from backend.core.config import settings # noqa: F401
|
| 372 |
+
|
| 373 |
+
client: QwenClient = app.state.qwen_client
|
| 374 |
+
prompt = str(body.get("prompt", "")).strip()
|
| 375 |
+
n = min(max(int(body.get("n", 1)), 1), 4)
|
| 376 |
+
model = _resolve_video_model(body.get("model"))
|
| 377 |
+
size = _normalize_size(body)
|
| 378 |
+
ref_images = _collect_images_from_body(body)
|
| 379 |
+
duration = body.get("duration") or body.get("duration_seconds")
|
| 380 |
+
|
| 381 |
+
await _set_video_task(task_id, status="processing", model=model, prompt=prompt[:200])
|
| 382 |
+
log.info("[T2V-ASYNC] start task_id=%s model=%s refs=%s size=%s", task_id, model, len(ref_images), size)
|
| 383 |
+
|
| 384 |
+
acc = None
|
| 385 |
+
chat_id = None
|
| 386 |
+
try:
|
| 387 |
+
prompt_text = _build_video_prompt(prompt, size)
|
| 388 |
+
if ref_images:
|
| 389 |
+
prompt_text = (
|
| 390 |
+
"Use the attached reference image(s) as strict character/appearance identity lock. "
|
| 391 |
+
"Keep face, hair, clothes and body proportions consistent with the reference. "
|
| 392 |
+
"Do not invent a different character.\n\n" + prompt_text
|
| 393 |
+
)
|
| 394 |
+
|
| 395 |
+
max_account_tries = 7
|
| 396 |
+
tried_emails: set[str] = set()
|
| 397 |
+
last_completion: Any = None
|
| 398 |
+
last_chat_detail: Any = None
|
| 399 |
+
video_urls: list[str] = []
|
| 400 |
+
|
| 401 |
+
for attempt in range(1, max_account_tries + 1):
|
| 402 |
+
if acc is None:
|
| 403 |
+
acc = await _acquire_video_account(client)
|
| 404 |
+
email = getattr(acc, "email", "") or ""
|
| 405 |
+
if email:
|
| 406 |
+
tried_emails.add(email)
|
| 407 |
+
|
| 408 |
+
files = []
|
| 409 |
+
img_url = None
|
| 410 |
+
if ref_images:
|
| 411 |
+
try:
|
| 412 |
+
files = await _upload_reference_images(client, acc, ref_images)
|
| 413 |
+
for f in files:
|
| 414 |
+
if isinstance(f, dict) and isinstance(f.get("url"), str) and f["url"].startswith("http"):
|
| 415 |
+
img_url = f["url"]
|
| 416 |
+
break
|
| 417 |
+
except Exception as upload_error:
|
| 418 |
+
log.warning("[T2V-ASYNC] reference upload failed on %s: %s", email, upload_error)
|
| 419 |
+
files = []
|
| 420 |
+
img_url = None
|
| 421 |
+
|
| 422 |
+
message_type = "i2v" if (files and img_url) else "t2v"
|
| 423 |
+
try:
|
| 424 |
+
chat_id = await client.create_chat(acc.token, model, chat_type="t2v")
|
| 425 |
+
chat_type = message_type
|
| 426 |
+
except Exception as chat_error:
|
| 427 |
+
log.warning("[T2V-ASYNC] create_chat failed on %s: %s", email, chat_error)
|
| 428 |
+
await _release_video_account(client, acc)
|
| 429 |
+
acc = None
|
| 430 |
+
chat_id = None
|
| 431 |
+
continue
|
| 432 |
+
|
| 433 |
+
log.info(
|
| 434 |
+
"[T2V-ASYNC] task=%s try=%s chat_id=%s account=%s chat_type=%s files=%s",
|
| 435 |
+
task_id,
|
| 436 |
+
attempt,
|
| 437 |
+
chat_id,
|
| 438 |
+
email,
|
| 439 |
+
chat_type,
|
| 440 |
+
len(files),
|
| 441 |
+
)
|
| 442 |
+
|
| 443 |
+
completion = await client.complete_once(
|
| 444 |
+
acc.token,
|
| 445 |
+
chat_id,
|
| 446 |
+
model,
|
| 447 |
+
prompt_text,
|
| 448 |
+
has_custom_tools=False,
|
| 449 |
+
files=files or None,
|
| 450 |
+
chat_type=chat_type,
|
| 451 |
+
size=size,
|
| 452 |
+
img_url=img_url,
|
| 453 |
+
)
|
| 454 |
+
last_completion = completion
|
| 455 |
+
|
| 456 |
+
if isinstance(completion, dict):
|
| 457 |
+
data_obj = completion.get("data") if isinstance(completion.get("data"), dict) else {}
|
| 458 |
+
code = str((data_obj or {}).get("code") or completion.get("code") or "")
|
| 459 |
+
details = str((data_obj or {}).get("details") or completion.get("details") or "")
|
| 460 |
+
success_flag = completion.get("success")
|
| 461 |
+
if success_flag is False or code in {"RateLimited", "rate_limited", "QuotaExceeded"} or "limit" in details.lower():
|
| 462 |
+
log.warning("[T2V-ASYNC] limited email=%s code=%s details=%s", email, code, details)
|
| 463 |
+
if chat_id:
|
| 464 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
| 465 |
+
chat_id = None
|
| 466 |
+
await _release_video_account(client, acc)
|
| 467 |
+
acc = None
|
| 468 |
+
if attempt >= max_account_tries:
|
| 469 |
+
await _set_video_task(
|
| 470 |
+
task_id,
|
| 471 |
+
status="failed",
|
| 472 |
+
error={"message": details or "RateLimited on all accounts", "code": code or "RateLimited"},
|
| 473 |
+
tried_accounts=list(tried_emails),
|
| 474 |
+
)
|
| 475 |
+
return
|
| 476 |
+
continue
|
| 477 |
+
|
| 478 |
+
chat_detail = None
|
| 479 |
+
try:
|
| 480 |
+
chat_detail = await client.get_chat(acc.token, chat_id)
|
| 481 |
+
last_chat_detail = chat_detail
|
| 482 |
+
except Exception as chat_error:
|
| 483 |
+
log.warning("[T2V-ASYNC] failed to fetch chat detail: %s", chat_error)
|
| 484 |
+
|
| 485 |
+
search_payload: list[Any] = [completion]
|
| 486 |
+
if chat_detail:
|
| 487 |
+
search_payload.append(chat_detail)
|
| 488 |
+
|
| 489 |
+
task_ids = _dedupe(_extract_task_ids(search_payload))
|
| 490 |
+
if task_ids:
|
| 491 |
+
log.info("[T2V-ASYNC] extracted upstream task IDs: %s", task_ids)
|
| 492 |
+
try:
|
| 493 |
+
task_result = await _poll_video_task(client, acc.token, task_ids[0])
|
| 494 |
+
search_payload.append(task_result)
|
| 495 |
+
except HTTPException as poll_err:
|
| 496 |
+
log.warning("[T2V-ASYNC] poll failed on %s: %s", email, poll_err.detail)
|
| 497 |
+
if chat_id:
|
| 498 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
| 499 |
+
chat_id = None
|
| 500 |
+
await _release_video_account(client, acc)
|
| 501 |
+
acc = None
|
| 502 |
+
continue
|
| 503 |
+
|
| 504 |
+
video_urls = _dedupe(_extract_video_urls(search_payload))
|
| 505 |
+
log.info("[T2V-ASYNC] extracted %s video URLs", len(video_urls))
|
| 506 |
+
if video_urls:
|
| 507 |
+
break
|
| 508 |
+
|
| 509 |
+
if chat_id:
|
| 510 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
| 511 |
+
chat_id = None
|
| 512 |
+
await _release_video_account(client, acc)
|
| 513 |
+
acc = None
|
| 514 |
+
|
| 515 |
+
if not video_urls:
|
| 516 |
+
debug_path = os.path.join(
|
| 517 |
+
os.path.dirname(os.path.dirname(os.path.dirname(__file__))),
|
| 518 |
+
"logs",
|
| 519 |
+
f"t2v-async-{task_id}.json",
|
| 520 |
+
)
|
| 521 |
+
try:
|
| 522 |
+
with open(debug_path, "w", encoding="utf-8") as f:
|
| 523 |
+
json.dump(
|
| 524 |
+
{"completion": last_completion, "chat": last_chat_detail, "tried": list(tried_emails)},
|
| 525 |
+
f,
|
| 526 |
+
ensure_ascii=False,
|
| 527 |
+
indent=2,
|
| 528 |
+
)
|
| 529 |
+
except Exception:
|
| 530 |
+
pass
|
| 531 |
+
await _set_video_task(
|
| 532 |
+
task_id,
|
| 533 |
+
status="failed",
|
| 534 |
+
error={"message": "Video generation produced no URL"},
|
| 535 |
+
tried_accounts=list(tried_emails),
|
| 536 |
+
)
|
| 537 |
+
return
|
| 538 |
+
|
| 539 |
+
url = video_urls[0]
|
| 540 |
+
meta: dict[str, Any] = {}
|
| 541 |
+
if duration is not None:
|
| 542 |
+
try:
|
| 543 |
+
meta["duration"] = int(float(duration))
|
| 544 |
+
except Exception:
|
| 545 |
+
pass
|
| 546 |
+
await _set_video_task(
|
| 547 |
+
task_id,
|
| 548 |
+
status="completed",
|
| 549 |
+
url=url,
|
| 550 |
+
urls=video_urls[:n],
|
| 551 |
+
metadata=meta,
|
| 552 |
+
data=[{"url": u, "revised_prompt": prompt} for u in video_urls[:n]],
|
| 553 |
+
)
|
| 554 |
+
log.info("[T2V-ASYNC] completed task_id=%s url=%s", task_id, url[:120])
|
| 555 |
+
except Exception as e:
|
| 556 |
+
log.exception("[T2V-ASYNC] task_id=%s failed: %s", task_id, e)
|
| 557 |
+
await _set_video_task(task_id, status="failed", error={"message": str(e)})
|
| 558 |
+
finally:
|
| 559 |
+
if acc is not None:
|
| 560 |
+
await _release_video_account(client, acc)
|
| 561 |
+
if chat_id:
|
| 562 |
+
asyncio.create_task(client.delete_chat(acc.token, chat_id))
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
@router.get("/v1/videos/generations/{task_id}")
|
| 566 |
+
@router.get("/v1/video/generations/{task_id}")
|
| 567 |
+
@router.get("/videos/generations/{task_id}")
|
| 568 |
+
@router.get("/video/generations/{task_id}")
|
| 569 |
+
async def get_video_task(task_id: str, request: Request):
|
| 570 |
+
"""NewAPI/ArcReel poll endpoint."""
|
| 571 |
+
from backend.core.config import API_KEYS, settings
|
| 572 |
+
|
| 573 |
+
token = _get_token(request)
|
| 574 |
+
if API_KEYS:
|
| 575 |
+
if token != settings.ADMIN_KEY and token not in API_KEYS:
|
| 576 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 577 |
+
|
| 578 |
+
task = await _get_video_task(task_id)
|
| 579 |
+
if not task:
|
| 580 |
+
raise HTTPException(status_code=404, detail=f"task not found: {task_id}")
|
| 581 |
+
|
| 582 |
+
status = task.get("status") or "queued"
|
| 583 |
+
body: dict[str, Any] = {
|
| 584 |
+
"task_id": task_id,
|
| 585 |
+
"status": status,
|
| 586 |
+
"model": task.get("model"),
|
| 587 |
+
}
|
| 588 |
+
if status == "completed":
|
| 589 |
+
body["url"] = task.get("url")
|
| 590 |
+
body["metadata"] = task.get("metadata") or {}
|
| 591 |
+
if task.get("data"):
|
| 592 |
+
body["data"] = task["data"]
|
| 593 |
+
elif status == "failed":
|
| 594 |
+
body["error"] = task.get("error") or {"message": "unknown"}
|
| 595 |
+
return JSONResponse(body)
|
| 596 |
+
|
| 597 |
+
|
| 598 |
+
@router.post("/v1/videos/generations")
|
| 599 |
+
@router.post("/v1/video/generations")
|
| 600 |
+
@router.post("/videos/generations")
|
| 601 |
+
@router.post("/video/generations")
|
| 602 |
+
async def create_video(request: Request):
|
| 603 |
+
"""Create video.
|
| 604 |
+
|
| 605 |
+
Default = **async NewAPI protocol** (immediate task_id) for ArcReel.
|
| 606 |
+
Pass ``{"wait": true}`` to block until finished and return the old
|
| 607 |
+
``{"data":[{"url":...}]}`` shape (for scripts / manual tests).
|
| 608 |
+
"""
|
| 609 |
+
from backend.core.config import API_KEYS, settings
|
| 610 |
+
|
| 611 |
+
token = _get_token(request)
|
| 612 |
+
if API_KEYS:
|
| 613 |
+
if token != settings.ADMIN_KEY and token not in API_KEYS:
|
| 614 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 615 |
+
|
| 616 |
+
try:
|
| 617 |
+
body = await request.json()
|
| 618 |
+
except Exception:
|
| 619 |
+
raise HTTPException(status_code=400, detail="Invalid JSON body")
|
| 620 |
+
|
| 621 |
+
prompt = str(body.get("prompt", "")).strip()
|
| 622 |
+
if not prompt:
|
| 623 |
+
raise HTTPException(status_code=400, detail="prompt is required")
|
| 624 |
+
|
| 625 |
+
await _purge_old_video_tasks()
|
| 626 |
+
wait = bool(body.get("wait") is True or str(body.get("wait", "")).lower() in {"1", "true", "yes"})
|
| 627 |
+
|
| 628 |
+
task_id = f"qv_{uuid.uuid4().hex[:16]}"
|
| 629 |
+
await _set_video_task(task_id, status="queued", model=_resolve_video_model(body.get("model")), prompt=prompt[:200])
|
| 630 |
+
asyncio.create_task(_run_video_job(request.app, task_id, body))
|
| 631 |
+
log.info("[T2V] queued task_id=%s wait=%s prompt=%r", task_id, wait, prompt[:80])
|
| 632 |
+
|
| 633 |
+
if not wait:
|
| 634 |
+
# ArcReel / NewAPI path — return immediately so create never times out.
|
| 635 |
+
return JSONResponse({"task_id": task_id, "status": "queued", "created": int(time.time())})
|
| 636 |
+
|
| 637 |
+
# Sync wait path for scripts.
|
| 638 |
+
deadline = time.monotonic() + int(body.get("timeout", 600) or 600)
|
| 639 |
+
while time.monotonic() < deadline:
|
| 640 |
+
task = await _get_video_task(task_id)
|
| 641 |
+
if not task:
|
| 642 |
+
break
|
| 643 |
+
st = task.get("status")
|
| 644 |
+
if st == "completed":
|
| 645 |
+
data = task.get("data") or [{"url": task.get("url"), "revised_prompt": prompt}]
|
| 646 |
+
return JSONResponse({"created": int(time.time()), "data": data, "task_id": task_id})
|
| 647 |
+
if st == "failed":
|
| 648 |
+
err = task.get("error") or {}
|
| 649 |
+
raise HTTPException(status_code=500, detail=err.get("message") or "video failed")
|
| 650 |
+
await asyncio.sleep(2)
|
| 651 |
+
|
| 652 |
+
raise HTTPException(status_code=504, detail={"message": "wait timeout", "task_id": task_id})
|
backend/core/__init__.py
ADDED
|
@@ -0,0 +1 @@
|
|
|
|
|
|
|
| 1 |
+
# Backend core package
|
backend/core/account_pool/__init__.py
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
账号池 - 完整实现(对齐 ds2api)
|
| 3 |
+
|
| 4 |
+
将 pool_core.py 和 pool_acquire.py 合并为完整的 AccountPool
|
| 5 |
+
"""
|
| 6 |
+
from backend.core.account_pool.pool_core import Account, AccountPool as CorePool
|
| 7 |
+
from backend.core.account_pool.pool_acquire import AccountAcquireMixin
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
class AccountPool(AccountAcquireMixin, CorePool):
|
| 11 |
+
"""
|
| 12 |
+
完整的账号池实现
|
| 13 |
+
|
| 14 |
+
对齐 ds2api 的 4 层并发控制:
|
| 15 |
+
1. max_inflight_per_account: 每账号最大并发
|
| 16 |
+
2. recommended_concurrency: 推荐并发值
|
| 17 |
+
3. max_queue_size: 等待队列上限
|
| 18 |
+
4. global_max_inflight: 全局最大并发
|
| 19 |
+
"""
|
| 20 |
+
pass
|
| 21 |
+
|
| 22 |
+
|
| 23 |
+
__all__ = ["Account", "AccountPool"]
|
backend/core/account_pool/pool_acquire.py
ADDED
|
@@ -0,0 +1,252 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
账号获取逻辑 - 对齐 ds2api 的 pool_acquire.go
|
| 3 |
+
"""
|
| 4 |
+
import asyncio
|
| 5 |
+
import logging
|
| 6 |
+
import random
|
| 7 |
+
import time
|
| 8 |
+
from typing import Optional, TYPE_CHECKING
|
| 9 |
+
|
| 10 |
+
from backend.core.config import settings
|
| 11 |
+
|
| 12 |
+
if TYPE_CHECKING:
|
| 13 |
+
from backend.core.account_pool.pool_core import Account
|
| 14 |
+
|
| 15 |
+
log = logging.getLogger("qwen2api.accounts.acquire")
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _jitter_seconds() -> float:
|
| 19 |
+
"""随机抖动"""
|
| 20 |
+
low = max(0, settings.REQUEST_JITTER_MIN_MS)
|
| 21 |
+
high = max(low, settings.REQUEST_JITTER_MAX_MS)
|
| 22 |
+
return random.uniform(low, high) / 1000.0
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
class AccountAcquireMixin:
|
| 26 |
+
"""账号获取逻辑混入类"""
|
| 27 |
+
|
| 28 |
+
async def _remove_waiter(self, waiter: asyncio.Event) -> None:
|
| 29 |
+
"""
|
| 30 |
+
从等待队列中移除 waiter(若仍在队列中)。
|
| 31 |
+
|
| 32 |
+
acquire_wait* 可能因超时返回;若不清理 waiter,队列长度会持续增长,
|
| 33 |
+
在 max_queue_size 较小时会出现“队列假满”并拒绝后续请求。
|
| 34 |
+
"""
|
| 35 |
+
async with self._lock:
|
| 36 |
+
queue = getattr(self._waiters_queue, "_queue", None)
|
| 37 |
+
if queue is None:
|
| 38 |
+
return
|
| 39 |
+
try:
|
| 40 |
+
queue.remove(waiter)
|
| 41 |
+
except ValueError:
|
| 42 |
+
# 已被 release() 的 notify 弹出,属于正常竞争场景
|
| 43 |
+
pass
|
| 44 |
+
|
| 45 |
+
async def acquire(self, exclude: Optional[set] = None) -> Optional["Account"]:
|
| 46 |
+
"""
|
| 47 |
+
立即获取账号(不等待)
|
| 48 |
+
对齐 ds2api 的 Acquire() 逻辑
|
| 49 |
+
"""
|
| 50 |
+
async with self._lock:
|
| 51 |
+
now = time.time()
|
| 52 |
+
|
| 53 |
+
# 检查全局并发限制
|
| 54 |
+
if not self._can_acquire_global():
|
| 55 |
+
return None
|
| 56 |
+
|
| 57 |
+
# 筛选可用账号
|
| 58 |
+
available = [a for a in self.accounts if a.is_available() and (not exclude or a.email not in exclude)]
|
| 59 |
+
if not available:
|
| 60 |
+
return None
|
| 61 |
+
|
| 62 |
+
# 筛选就绪账号(未达到并发上限且冷却完成)
|
| 63 |
+
ready = [a for a in available if a.inflight < self.max_inflight_per_account and a.next_available_at() <= now]
|
| 64 |
+
if not ready:
|
| 65 |
+
return None
|
| 66 |
+
|
| 67 |
+
# 按负载排序:优先选择 inflight 最少的账号
|
| 68 |
+
ready.sort(key=lambda a: (a.inflight, a.last_request_started or 0.0, a.last_used or 0.0))
|
| 69 |
+
best = ready[0]
|
| 70 |
+
|
| 71 |
+
# 分配账号
|
| 72 |
+
best.inflight += 1
|
| 73 |
+
best.last_used = now
|
| 74 |
+
best.last_request_started = now + _jitter_seconds()
|
| 75 |
+
self.global_in_use += 1
|
| 76 |
+
self._sticky_email = best.email if len(ready) == 1 else None
|
| 77 |
+
|
| 78 |
+
return best
|
| 79 |
+
|
| 80 |
+
async def acquire_preferred(self, preferred_email: Optional[str] = None, exclude: Optional[set] = None) -> Optional["Account"]:
|
| 81 |
+
"""
|
| 82 |
+
优先获取指定账号
|
| 83 |
+
对齐 ds2api 的 AcquirePreferred() 逻辑
|
| 84 |
+
"""
|
| 85 |
+
if not preferred_email:
|
| 86 |
+
return await self.acquire(exclude)
|
| 87 |
+
|
| 88 |
+
async with self._lock:
|
| 89 |
+
now = time.time()
|
| 90 |
+
|
| 91 |
+
# 检查全局并发限制
|
| 92 |
+
if not self._can_acquire_global():
|
| 93 |
+
return None
|
| 94 |
+
|
| 95 |
+
# 查找指定账号
|
| 96 |
+
preferred = next((a for a in self.accounts if a.email == preferred_email), None)
|
| 97 |
+
if (
|
| 98 |
+
preferred
|
| 99 |
+
and preferred.is_available()
|
| 100 |
+
and preferred.inflight < self.max_inflight_per_account
|
| 101 |
+
and preferred.next_available_at() <= now
|
| 102 |
+
and (not exclude or preferred.email not in exclude)
|
| 103 |
+
):
|
| 104 |
+
preferred.inflight += 1
|
| 105 |
+
preferred.last_used = now
|
| 106 |
+
preferred.last_request_started = now + _jitter_seconds()
|
| 107 |
+
self.global_in_use += 1
|
| 108 |
+
self._sticky_email = preferred.email
|
| 109 |
+
return preferred
|
| 110 |
+
|
| 111 |
+
# 指定账号不可用,回退到普通获取
|
| 112 |
+
return await self.acquire(exclude)
|
| 113 |
+
|
| 114 |
+
async def acquire_wait(self, timeout: float = 60, exclude: Optional[set] = None) -> Optional["Account"]:
|
| 115 |
+
"""
|
| 116 |
+
等待获取账号(带超时)
|
| 117 |
+
对齐 ds2api 的 AcquireWait() 逻辑
|
| 118 |
+
"""
|
| 119 |
+
deadline = time.time() + timeout
|
| 120 |
+
|
| 121 |
+
while True:
|
| 122 |
+
# 尝试立即获取
|
| 123 |
+
acc = await self.acquire(exclude)
|
| 124 |
+
if acc:
|
| 125 |
+
return acc
|
| 126 |
+
|
| 127 |
+
# 检查是否还有候选账号
|
| 128 |
+
async with self._lock:
|
| 129 |
+
candidates = [a for a in self.accounts if a.valid and (not exclude or a.email not in exclude)]
|
| 130 |
+
if not candidates:
|
| 131 |
+
return None
|
| 132 |
+
|
| 133 |
+
# 计算下次可用时间
|
| 134 |
+
next_ready_at = min((a.next_available_at() for a in candidates), default=time.time())
|
| 135 |
+
|
| 136 |
+
# 检查超时
|
| 137 |
+
remaining = deadline - time.time()
|
| 138 |
+
if remaining <= 0:
|
| 139 |
+
return None
|
| 140 |
+
|
| 141 |
+
# 检查队列是否已满
|
| 142 |
+
if not self._can_queue():
|
| 143 |
+
log.warning(f"[AccountPool] 等待队列已满 ({self._waiters_queue.qsize()}/{self.max_queue_size})")
|
| 144 |
+
return None
|
| 145 |
+
|
| 146 |
+
# 加入等待队列
|
| 147 |
+
waiter = asyncio.Event()
|
| 148 |
+
await self._waiters_queue.put(waiter)
|
| 149 |
+
|
| 150 |
+
# 计算等待时间
|
| 151 |
+
wait_timeout = min(remaining, max(0.05, next_ready_at - time.time() + 0.05))
|
| 152 |
+
|
| 153 |
+
try:
|
| 154 |
+
await asyncio.wait_for(waiter.wait(), timeout=wait_timeout)
|
| 155 |
+
except asyncio.TimeoutError:
|
| 156 |
+
pass
|
| 157 |
+
finally:
|
| 158 |
+
await self._remove_waiter(waiter)
|
| 159 |
+
|
| 160 |
+
async def acquire_wait_preferred(
|
| 161 |
+
self, preferred_email: Optional[str] = None, timeout: float = 60, exclude: Optional[set] = None
|
| 162 |
+
) -> Optional["Account"]:
|
| 163 |
+
"""
|
| 164 |
+
等待获取指定账号
|
| 165 |
+
对齐 ds2api 的 AcquireWaitPreferred() 逻辑
|
| 166 |
+
"""
|
| 167 |
+
deadline = time.time() + timeout
|
| 168 |
+
|
| 169 |
+
while True:
|
| 170 |
+
acc = await self.acquire_preferred(preferred_email, exclude)
|
| 171 |
+
if acc:
|
| 172 |
+
return acc
|
| 173 |
+
|
| 174 |
+
remaining = deadline - time.time()
|
| 175 |
+
if remaining <= 0:
|
| 176 |
+
return None
|
| 177 |
+
|
| 178 |
+
if not self._can_queue():
|
| 179 |
+
return None
|
| 180 |
+
|
| 181 |
+
waiter = asyncio.Event()
|
| 182 |
+
await self._waiters_queue.put(waiter)
|
| 183 |
+
|
| 184 |
+
try:
|
| 185 |
+
await asyncio.wait_for(waiter.wait(), timeout=min(remaining, 0.5))
|
| 186 |
+
except asyncio.TimeoutError:
|
| 187 |
+
pass
|
| 188 |
+
finally:
|
| 189 |
+
await self._remove_waiter(waiter)
|
| 190 |
+
|
| 191 |
+
def release(self, acc: "Account"):
|
| 192 |
+
"""
|
| 193 |
+
释放账号
|
| 194 |
+
对齐 ds2api 的 Release() 逻辑
|
| 195 |
+
"""
|
| 196 |
+
if not acc or not acc.email:
|
| 197 |
+
return
|
| 198 |
+
|
| 199 |
+
acc.inflight = max(0, acc.inflight - 1)
|
| 200 |
+
acc.last_request_finished = time.time()
|
| 201 |
+
self.global_in_use = max(0, self.global_in_use - 1)
|
| 202 |
+
|
| 203 |
+
# 唤醒等待队列中的第一个
|
| 204 |
+
self._notify_waiter()
|
| 205 |
+
|
| 206 |
+
def _notify_waiter(self):
|
| 207 |
+
"""
|
| 208 |
+
唤醒等待队列中的第一个等待者
|
| 209 |
+
对齐 ds2api 的 notifyWaiterLocked()
|
| 210 |
+
"""
|
| 211 |
+
if self._waiters_queue.empty():
|
| 212 |
+
return
|
| 213 |
+
|
| 214 |
+
try:
|
| 215 |
+
waiter = self._waiters_queue.get_nowait()
|
| 216 |
+
waiter.set() # 唤醒
|
| 217 |
+
except asyncio.QueueEmpty:
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
def mark_invalid(self, acc: "Account", reason: str = "invalid", error_message: str = ""):
|
| 221 |
+
"""标记账号为不可用"""
|
| 222 |
+
acc.valid = False
|
| 223 |
+
acc.status_code = reason or "invalid"
|
| 224 |
+
acc.last_error = error_message or acc.last_error
|
| 225 |
+
acc.consecutive_failures += 1
|
| 226 |
+
if reason == "pending_activation":
|
| 227 |
+
acc.activation_pending = True
|
| 228 |
+
if self._sticky_email == acc.email:
|
| 229 |
+
self._sticky_email = None
|
| 230 |
+
log.warning(f"[账号] {acc.email} 已标记为不可用,状态={acc.status_code}")
|
| 231 |
+
|
| 232 |
+
def mark_success(self, acc: "Account"):
|
| 233 |
+
"""标记账号请求成功"""
|
| 234 |
+
acc.consecutive_failures = 0
|
| 235 |
+
acc.rate_limit_strikes = 0
|
| 236 |
+
if acc.status_code == "rate_limited":
|
| 237 |
+
acc.status_code = "valid"
|
| 238 |
+
if not acc.activation_pending:
|
| 239 |
+
acc.valid = True
|
| 240 |
+
|
| 241 |
+
def mark_rate_limited(self, acc: "Account", cooldown: int | None = None, error_message: str = ""):
|
| 242 |
+
"""标记账号被限流"""
|
| 243 |
+
acc.rate_limit_strikes += 1
|
| 244 |
+
base = cooldown if cooldown is not None else settings.RATE_LIMIT_BASE_COOLDOWN
|
| 245 |
+
dynamic = min(settings.RATE_LIMIT_MAX_COOLDOWN, int(base * (2 ** max(0, acc.rate_limit_strikes - 1))))
|
| 246 |
+
dynamic += int(_jitter_seconds())
|
| 247 |
+
acc.rate_limited_until = time.time() + dynamic
|
| 248 |
+
acc.status_code = "rate_limited"
|
| 249 |
+
acc.last_error = error_message or acc.last_error
|
| 250 |
+
if self._sticky_email == acc.email:
|
| 251 |
+
self._sticky_email = None
|
| 252 |
+
log.warning(f"[账号] {acc.email} 已限流冷却 {dynamic} 秒")
|
backend/core/account_pool/pool_core.py
ADDED
|
@@ -0,0 +1,216 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
| 1 |
+
"""
|
| 2 |
+
账号池核心逻辑 - 对齐 ds2api 的 pool_core.go
|
| 3 |
+
"""
|
| 4 |
+
import asyncio
|
| 5 |
+
import logging
|
| 6 |
+
import time
|
| 7 |
+
from typing import Optional
|
| 8 |
+
|
| 9 |
+
from backend.core.database import AsyncJsonDB
|
| 10 |
+
from backend.core.config import settings
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger("qwen2api.accounts.core")
|
| 13 |
+
|
| 14 |
+
|
| 15 |
+
class Account:
|
| 16 |
+
"""账号对象"""
|
| 17 |
+
def __init__(
|
| 18 |
+
self,
|
| 19 |
+
email="",
|
| 20 |
+
password="",
|
| 21 |
+
token="",
|
| 22 |
+
cookies="",
|
| 23 |
+
username="",
|
| 24 |
+
activation_pending=False,
|
| 25 |
+
status_code="",
|
| 26 |
+
last_error="",
|
| 27 |
+
**kwargs,
|
| 28 |
+
):
|
| 29 |
+
self.email = email
|
| 30 |
+
self.password = password
|
| 31 |
+
self.token = token
|
| 32 |
+
self.cookies = cookies
|
| 33 |
+
self.username = username
|
| 34 |
+
self.activation_pending = activation_pending
|
| 35 |
+
self.valid = not activation_pending
|
| 36 |
+
self.last_used = 0.0
|
| 37 |
+
self.inflight = 0
|
| 38 |
+
self.rate_limited_until = 0.0
|
| 39 |
+
self.healing = False
|
| 40 |
+
self.status_code = status_code or ("pending_activation" if activation_pending else "valid")
|
| 41 |
+
self.last_error = last_error or ""
|
| 42 |
+
self.last_request_started = float(kwargs.get("last_request_started", 0.0) or 0.0)
|
| 43 |
+
self.last_request_finished = float(kwargs.get("last_request_finished", 0.0) or 0.0)
|
| 44 |
+
self.consecutive_failures = int(kwargs.get("consecutive_failures", 0) or 0)
|
| 45 |
+
self.rate_limit_strikes = int(kwargs.get("rate_limit_strikes", 0) or 0)
|
| 46 |
+
|
| 47 |
+
def is_rate_limited(self) -> bool:
|
| 48 |
+
return self.rate_limited_until > time.time()
|
| 49 |
+
|
| 50 |
+
def is_available(self) -> bool:
|
| 51 |
+
return self.valid and not self.is_rate_limited()
|
| 52 |
+
|
| 53 |
+
def next_available_at(self) -> float:
|
| 54 |
+
min_interval = max(0, settings.ACCOUNT_MIN_INTERVAL_MS) / 1000.0
|
| 55 |
+
return max(self.rate_limited_until, self.last_request_started + min_interval)
|
| 56 |
+
|
| 57 |
+
def get_status_code(self) -> str:
|
| 58 |
+
if self.activation_pending:
|
| 59 |
+
return "pending_activation"
|
| 60 |
+
if self.is_rate_limited():
|
| 61 |
+
return "rate_limited"
|
| 62 |
+
if self.valid:
|
| 63 |
+
return "valid"
|
| 64 |
+
if self.status_code == "banned":
|
| 65 |
+
return "banned"
|
| 66 |
+
if self.status_code == "auth_error":
|
| 67 |
+
return "auth_error"
|
| 68 |
+
return self.status_code or "invalid"
|
| 69 |
+
|
| 70 |
+
def get_status_text(self) -> str:
|
| 71 |
+
status_map = {
|
| 72 |
+
"valid": "正常",
|
| 73 |
+
"pending_activation": "待激活",
|
| 74 |
+
"rate_limited": "限流",
|
| 75 |
+
"banned": "封禁",
|
| 76 |
+
"auth_error": "鉴权失败",
|
| 77 |
+
"invalid": "失效",
|
| 78 |
+
"unknown": "未知",
|
| 79 |
+
}
|
| 80 |
+
return status_map.get(self.get_status_code(), "未知")
|
| 81 |
+
|
| 82 |
+
def to_dict(self):
|
| 83 |
+
return {
|
| 84 |
+
"email": self.email,
|
| 85 |
+
"password": self.password,
|
| 86 |
+
"token": self.token,
|
| 87 |
+
"cookies": self.cookies,
|
| 88 |
+
"username": self.username,
|
| 89 |
+
"activation_pending": self.activation_pending,
|
| 90 |
+
"status_code": self.status_code,
|
| 91 |
+
"last_error": self.last_error,
|
| 92 |
+
"last_request_started": self.last_request_started,
|
| 93 |
+
"last_request_finished": self.last_request_finished,
|
| 94 |
+
"consecutive_failures": self.consecutive_failures,
|
| 95 |
+
"rate_limit_strikes": self.rate_limit_strikes,
|
| 96 |
+
}
|
| 97 |
+
|
| 98 |
+
|
| 99 |
+
class AccountPool:
|
| 100 |
+
"""
|
| 101 |
+
账号池 - 对齐 ds2api 的 4 层并发控制
|
| 102 |
+
|
| 103 |
+
4 层限流:
|
| 104 |
+
1. maxInflightPerAccount: 每账号最大并发
|
| 105 |
+
2. recommendedConcurrency: 推荐并发值(账号数 × 每账号并发)
|
| 106 |
+
3. maxQueueSize: 等待队列上限
|
| 107 |
+
4. globalMaxInflight: 全局最大并发
|
| 108 |
+
"""
|
| 109 |
+
|
| 110 |
+
def __init__(self, db: AsyncJsonDB, max_inflight: int = settings.MAX_INFLIGHT_PER_ACCOUNT):
|
| 111 |
+
self.db = db
|
| 112 |
+
self.accounts: list[Account] = []
|
| 113 |
+
self._lock = asyncio.Lock()
|
| 114 |
+
|
| 115 |
+
# 4 层并发控制(对齐 ds2api)
|
| 116 |
+
self.max_inflight_per_account = max_inflight
|
| 117 |
+
self.recommended_concurrency = 0
|
| 118 |
+
self.max_queue_size = 0
|
| 119 |
+
self.global_max_inflight = 0
|
| 120 |
+
|
| 121 |
+
# 等待队列(使用 asyncio.Queue 更接近 Go channel)
|
| 122 |
+
self._waiters_queue: asyncio.Queue = asyncio.Queue()
|
| 123 |
+
self._sticky_email: Optional[str] = None
|
| 124 |
+
|
| 125 |
+
# 全局并发计数
|
| 126 |
+
self.global_in_use = 0
|
| 127 |
+
|
| 128 |
+
async def load(self):
|
| 129 |
+
"""加载账号并初始化并发参数"""
|
| 130 |
+
data = await self.db.load()
|
| 131 |
+
self.accounts = [Account(**d) for d in data] if isinstance(data, list) else []
|
| 132 |
+
self._reset_concurrency_limits()
|
| 133 |
+
log.info(f"Loaded {len(self.accounts)} upstream account(s)")
|
| 134 |
+
|
| 135 |
+
def _reset_concurrency_limits(self):
|
| 136 |
+
"""重置并发限制 - 对齐 ds2api 的 Reset() 逻辑"""
|
| 137 |
+
account_count = len([a for a in self.accounts if a.is_available()])
|
| 138 |
+
|
| 139 |
+
# 计算推荐并发值(对齐 ds2api)
|
| 140 |
+
self.recommended_concurrency = account_count * self.max_inflight_per_account
|
| 141 |
+
|
| 142 |
+
# 队列上限 = 推荐并发值(可配置)
|
| 143 |
+
self.max_queue_size = self.recommended_concurrency
|
| 144 |
+
|
| 145 |
+
# 全局并发上限 = 推荐并发值(可配置)
|
| 146 |
+
self.global_max_inflight = self.recommended_concurrency
|
| 147 |
+
|
| 148 |
+
log.info(
|
| 149 |
+
f"[init_account_queue] initialized: "
|
| 150 |
+
f"total={account_count}, "
|
| 151 |
+
f"max_inflight_per_account={self.max_inflight_per_account}, "
|
| 152 |
+
f"global_max_inflight={self.global_max_inflight}, "
|
| 153 |
+
f"recommended_concurrency={self.recommended_concurrency}, "
|
| 154 |
+
f"max_queue_size={self.max_queue_size}"
|
| 155 |
+
)
|
| 156 |
+
|
| 157 |
+
async def save(self):
|
| 158 |
+
await self.db.save([a.to_dict() for a in self.accounts])
|
| 159 |
+
|
| 160 |
+
async def add(self, account: Account):
|
| 161 |
+
async with self._lock:
|
| 162 |
+
self.accounts = [a for a in self.accounts if a.email != account.email]
|
| 163 |
+
self.accounts.append(account)
|
| 164 |
+
await self.save()
|
| 165 |
+
self._reset_concurrency_limits()
|
| 166 |
+
|
| 167 |
+
async def remove(self, email: str):
|
| 168 |
+
async with self._lock:
|
| 169 |
+
self.accounts = [a for a in self.accounts if a.email != email]
|
| 170 |
+
await self.save()
|
| 171 |
+
self._reset_concurrency_limits()
|
| 172 |
+
|
| 173 |
+
def set_max_inflight(self, value: int):
|
| 174 |
+
self.max_inflight_per_account = max(1, int(value))
|
| 175 |
+
self._reset_concurrency_limits()
|
| 176 |
+
|
| 177 |
+
def get_by_email(self, email: str) -> Optional[Account]:
|
| 178 |
+
return next((a for a in self.accounts if a.email == email), None)
|
| 179 |
+
|
| 180 |
+
def _can_acquire_global(self) -> bool:
|
| 181 |
+
"""检查全局并发限制"""
|
| 182 |
+
if self.global_max_inflight <= 0:
|
| 183 |
+
return True
|
| 184 |
+
return self.global_in_use < self.global_max_inflight
|
| 185 |
+
|
| 186 |
+
def _can_queue(self) -> bool:
|
| 187 |
+
"""检查是否可以加入等待队列"""
|
| 188 |
+
if self.max_queue_size <= 0:
|
| 189 |
+
return False
|
| 190 |
+
return self._waiters_queue.qsize() < self.max_queue_size
|
| 191 |
+
|
| 192 |
+
def status(self):
|
| 193 |
+
"""返回账号池状态"""
|
| 194 |
+
available = [a for a in self.accounts if a.is_available()]
|
| 195 |
+
rate_limited = [a for a in self.accounts if a.get_status_code() == "rate_limited"]
|
| 196 |
+
invalid = [a for a in self.accounts if a.get_status_code() not in ("valid", "rate_limited")]
|
| 197 |
+
activation_pending = [a for a in self.accounts if a.get_status_code() == "pending_activation"]
|
| 198 |
+
banned = [a for a in self.accounts if a.get_status_code() == "banned"]
|
| 199 |
+
in_use = sum(a.inflight for a in self.accounts)
|
| 200 |
+
|
| 201 |
+
return {
|
| 202 |
+
"total": len(self.accounts),
|
| 203 |
+
"valid": len(available),
|
| 204 |
+
"rate_limited": len(rate_limited),
|
| 205 |
+
"invalid": len(invalid),
|
| 206 |
+
"activation_pending": len(activation_pending),
|
| 207 |
+
"banned": len(banned),
|
| 208 |
+
"in_use": in_use,
|
| 209 |
+
"global_in_use": self.global_in_use,
|
| 210 |
+
"max_inflight_per_account": self.max_inflight_per_account,
|
| 211 |
+
"recommended_concurrency": self.recommended_concurrency,
|
| 212 |
+
"max_queue_size": self.max_queue_size,
|
| 213 |
+
"global_max_inflight": self.global_max_inflight,
|
| 214 |
+
"waiting": self._waiters_queue.qsize(),
|
| 215 |
+
"account_min_interval_ms": getattr(settings, "ACCOUNT_MIN_INTERVAL_MS", 0),
|
| 216 |
+
}
|
backend/core/account_pool_old.py
ADDED
|
@@ -0,0 +1,275 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
import random
|
| 4 |
+
import time
|
| 5 |
+
from typing import Optional
|
| 6 |
+
from backend.core.database import AsyncJsonDB
|
| 7 |
+
from backend.core.config import settings
|
| 8 |
+
|
| 9 |
+
log = logging.getLogger("qwen2api.accounts")
|
| 10 |
+
|
| 11 |
+
|
| 12 |
+
def _jitter_seconds() -> float:
|
| 13 |
+
low = max(0, settings.REQUEST_JITTER_MIN_MS)
|
| 14 |
+
high = max(low, settings.REQUEST_JITTER_MAX_MS)
|
| 15 |
+
return random.uniform(low, high) / 1000.0
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
class Account:
|
| 19 |
+
def __init__(
|
| 20 |
+
self,
|
| 21 |
+
email="",
|
| 22 |
+
password="",
|
| 23 |
+
token="",
|
| 24 |
+
cookies="",
|
| 25 |
+
username="",
|
| 26 |
+
activation_pending=False,
|
| 27 |
+
status_code="",
|
| 28 |
+
last_error="",
|
| 29 |
+
**kwargs,
|
| 30 |
+
):
|
| 31 |
+
self.email = email
|
| 32 |
+
self.password = password
|
| 33 |
+
self.token = token
|
| 34 |
+
self.cookies = cookies
|
| 35 |
+
self.username = username
|
| 36 |
+
self.activation_pending = activation_pending
|
| 37 |
+
self.valid = not activation_pending
|
| 38 |
+
self.last_used = 0.0
|
| 39 |
+
self.inflight = 0
|
| 40 |
+
self.rate_limited_until = 0.0
|
| 41 |
+
self.healing = False
|
| 42 |
+
self.status_code = status_code or ("pending_activation" if activation_pending else "valid")
|
| 43 |
+
self.last_error = last_error or ""
|
| 44 |
+
self.last_request_started = float(kwargs.get("last_request_started", 0.0) or 0.0)
|
| 45 |
+
self.last_request_finished = float(kwargs.get("last_request_finished", 0.0) or 0.0)
|
| 46 |
+
self.consecutive_failures = int(kwargs.get("consecutive_failures", 0) or 0)
|
| 47 |
+
self.rate_limit_strikes = int(kwargs.get("rate_limit_strikes", 0) or 0)
|
| 48 |
+
|
| 49 |
+
def is_rate_limited(self) -> bool:
|
| 50 |
+
return self.rate_limited_until > time.time()
|
| 51 |
+
|
| 52 |
+
def is_available(self) -> bool:
|
| 53 |
+
return self.valid and not self.is_rate_limited()
|
| 54 |
+
|
| 55 |
+
def next_available_at(self) -> float:
|
| 56 |
+
min_interval = max(0, settings.ACCOUNT_MIN_INTERVAL_MS) / 1000.0
|
| 57 |
+
return max(self.rate_limited_until, self.last_request_started + min_interval)
|
| 58 |
+
|
| 59 |
+
def get_status_code(self) -> str:
|
| 60 |
+
if self.activation_pending:
|
| 61 |
+
return "pending_activation"
|
| 62 |
+
if self.is_rate_limited():
|
| 63 |
+
return "rate_limited"
|
| 64 |
+
if self.valid:
|
| 65 |
+
return "valid"
|
| 66 |
+
if self.status_code == "banned":
|
| 67 |
+
return "banned"
|
| 68 |
+
if self.status_code == "auth_error":
|
| 69 |
+
return "auth_error"
|
| 70 |
+
return self.status_code or "invalid"
|
| 71 |
+
|
| 72 |
+
def get_status_text(self) -> str:
|
| 73 |
+
status_map = {
|
| 74 |
+
"valid": "正常",
|
| 75 |
+
"pending_activation": "待激活",
|
| 76 |
+
"rate_limited": "限流",
|
| 77 |
+
"banned": "封禁",
|
| 78 |
+
"auth_error": "鉴权失败",
|
| 79 |
+
"invalid": "失效",
|
| 80 |
+
"unknown": "未知",
|
| 81 |
+
}
|
| 82 |
+
return status_map.get(self.get_status_code(), "未知")
|
| 83 |
+
|
| 84 |
+
def to_dict(self):
|
| 85 |
+
return {
|
| 86 |
+
"email": self.email,
|
| 87 |
+
"password": self.password,
|
| 88 |
+
"token": self.token,
|
| 89 |
+
"cookies": self.cookies,
|
| 90 |
+
"username": self.username,
|
| 91 |
+
"activation_pending": self.activation_pending,
|
| 92 |
+
"status_code": self.status_code,
|
| 93 |
+
"last_error": self.last_error,
|
| 94 |
+
"last_request_started": self.last_request_started,
|
| 95 |
+
"last_request_finished": self.last_request_finished,
|
| 96 |
+
"consecutive_failures": self.consecutive_failures,
|
| 97 |
+
"rate_limit_strikes": self.rate_limit_strikes,
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
class AccountPool:
|
| 102 |
+
def __init__(self, db: AsyncJsonDB, max_inflight: int = settings.MAX_INFLIGHT_PER_ACCOUNT):
|
| 103 |
+
self.db = db
|
| 104 |
+
self.max_inflight = max_inflight
|
| 105 |
+
self.accounts: list[Account] = []
|
| 106 |
+
self._lock = asyncio.Lock()
|
| 107 |
+
self._waiters: list[asyncio.Event] = []
|
| 108 |
+
self._sticky_email: Optional[str] = None
|
| 109 |
+
|
| 110 |
+
async def load(self):
|
| 111 |
+
data = await self.db.load()
|
| 112 |
+
self.accounts = [Account(**d) for d in data] if isinstance(data, list) else []
|
| 113 |
+
log.info(f"Loaded {len(self.accounts)} upstream account(s)")
|
| 114 |
+
|
| 115 |
+
async def save(self):
|
| 116 |
+
await self.db.save([a.to_dict() for a in self.accounts])
|
| 117 |
+
|
| 118 |
+
async def add(self, account: Account):
|
| 119 |
+
async with self._lock:
|
| 120 |
+
self.accounts = [a for a in self.accounts if a.email != account.email]
|
| 121 |
+
self.accounts.append(account)
|
| 122 |
+
await self.save()
|
| 123 |
+
|
| 124 |
+
async def remove(self, email: str):
|
| 125 |
+
async with self._lock:
|
| 126 |
+
self.accounts = [a for a in self.accounts if a.email != email]
|
| 127 |
+
await self.save()
|
| 128 |
+
|
| 129 |
+
def set_max_inflight(self, value: int):
|
| 130 |
+
self.max_inflight = max(1, int(value))
|
| 131 |
+
|
| 132 |
+
def get_by_email(self, email: str) -> Optional[Account]:
|
| 133 |
+
return next((a for a in self.accounts if a.email == email), None)
|
| 134 |
+
|
| 135 |
+
async def acquire_preferred(self, preferred_email: str | None = None, exclude: set = None) -> Optional[Account]:
|
| 136 |
+
if not preferred_email:
|
| 137 |
+
return await self.acquire(exclude)
|
| 138 |
+
async with self._lock:
|
| 139 |
+
now = time.time()
|
| 140 |
+
preferred = next((a for a in self.accounts if a.email == preferred_email), None)
|
| 141 |
+
if preferred and preferred.is_available() and preferred.inflight < self.max_inflight and preferred.next_available_at() <= now and (not exclude or preferred.email not in exclude):
|
| 142 |
+
preferred.inflight += 1
|
| 143 |
+
preferred.last_used = now
|
| 144 |
+
preferred.last_request_started = now + _jitter_seconds()
|
| 145 |
+
self._sticky_email = preferred.email
|
| 146 |
+
return preferred
|
| 147 |
+
return await self.acquire(exclude)
|
| 148 |
+
|
| 149 |
+
async def acquire_wait_preferred(self, preferred_email: str | None = None, timeout: float = 60, exclude: set = None) -> Optional[Account]:
|
| 150 |
+
deadline = time.time() + timeout
|
| 151 |
+
while True:
|
| 152 |
+
acc = await self.acquire_preferred(preferred_email, exclude)
|
| 153 |
+
if acc:
|
| 154 |
+
return acc
|
| 155 |
+
remaining = deadline - time.time()
|
| 156 |
+
if remaining <= 0:
|
| 157 |
+
return None
|
| 158 |
+
evt = asyncio.Event()
|
| 159 |
+
self._waiters.append(evt)
|
| 160 |
+
try:
|
| 161 |
+
await asyncio.wait_for(evt.wait(), timeout=min(remaining, 0.5))
|
| 162 |
+
except asyncio.TimeoutError:
|
| 163 |
+
pass
|
| 164 |
+
finally:
|
| 165 |
+
if evt in self._waiters:
|
| 166 |
+
self._waiters.remove(evt)
|
| 167 |
+
|
| 168 |
+
async def acquire(self, exclude: set = None) -> Optional[Account]:
|
| 169 |
+
async with self._lock:
|
| 170 |
+
now = time.time()
|
| 171 |
+
available = [a for a in self.accounts if a.is_available() and (not exclude or a.email not in exclude)]
|
| 172 |
+
if not available:
|
| 173 |
+
return None
|
| 174 |
+
|
| 175 |
+
ready = [a for a in available if a.inflight < self.max_inflight and a.next_available_at() <= now]
|
| 176 |
+
if not ready:
|
| 177 |
+
return None
|
| 178 |
+
|
| 179 |
+
ready.sort(key=lambda a: (a.inflight, a.last_request_started or 0.0, a.last_used or 0.0))
|
| 180 |
+
best = ready[0]
|
| 181 |
+
best.inflight += 1
|
| 182 |
+
best.last_used = now
|
| 183 |
+
best.last_request_started = now + _jitter_seconds()
|
| 184 |
+
self._sticky_email = best.email if len(ready) == 1 else None
|
| 185 |
+
return best
|
| 186 |
+
|
| 187 |
+
async def acquire_wait(self, timeout: float = 60, exclude: set = None) -> Optional[Account]:
|
| 188 |
+
deadline = time.time() + timeout
|
| 189 |
+
while True:
|
| 190 |
+
acc = await self.acquire(exclude)
|
| 191 |
+
if acc:
|
| 192 |
+
return acc
|
| 193 |
+
|
| 194 |
+
async with self._lock:
|
| 195 |
+
candidates = [
|
| 196 |
+
a for a in self.accounts
|
| 197 |
+
if a.valid and (not exclude or a.email not in exclude)
|
| 198 |
+
]
|
| 199 |
+
if not candidates:
|
| 200 |
+
return None
|
| 201 |
+
next_ready_at = min((a.next_available_at() for a in candidates), default=time.time())
|
| 202 |
+
|
| 203 |
+
remaining = deadline - time.time()
|
| 204 |
+
if remaining <= 0:
|
| 205 |
+
return None
|
| 206 |
+
|
| 207 |
+
evt = asyncio.Event()
|
| 208 |
+
self._waiters.append(evt)
|
| 209 |
+
wait_timeout = min(remaining, max(0.05, next_ready_at - time.time() + 0.05))
|
| 210 |
+
try:
|
| 211 |
+
await asyncio.wait_for(evt.wait(), timeout=wait_timeout)
|
| 212 |
+
except asyncio.TimeoutError:
|
| 213 |
+
pass
|
| 214 |
+
finally:
|
| 215 |
+
if evt in self._waiters:
|
| 216 |
+
self._waiters.remove(evt)
|
| 217 |
+
|
| 218 |
+
def release(self, acc: Account):
|
| 219 |
+
acc.inflight = max(0, acc.inflight - 1)
|
| 220 |
+
acc.last_request_finished = time.time()
|
| 221 |
+
if self._waiters:
|
| 222 |
+
evt = self._waiters.pop(0)
|
| 223 |
+
evt.set()
|
| 224 |
+
|
| 225 |
+
def mark_invalid(self, acc: Account, reason: str = "invalid", error_message: str = ""):
|
| 226 |
+
acc.valid = False
|
| 227 |
+
acc.status_code = reason or "invalid"
|
| 228 |
+
acc.last_error = error_message or acc.last_error
|
| 229 |
+
acc.consecutive_failures += 1
|
| 230 |
+
if reason == "pending_activation":
|
| 231 |
+
acc.activation_pending = True
|
| 232 |
+
if self._sticky_email == acc.email:
|
| 233 |
+
self._sticky_email = None
|
| 234 |
+
log.warning(f"[账号] {acc.email} 已标记为不可用,状态={acc.status_code}")
|
| 235 |
+
|
| 236 |
+
def mark_success(self, acc: Account):
|
| 237 |
+
acc.consecutive_failures = 0
|
| 238 |
+
acc.rate_limit_strikes = 0
|
| 239 |
+
if acc.status_code == "rate_limited":
|
| 240 |
+
acc.status_code = "valid"
|
| 241 |
+
if not acc.activation_pending:
|
| 242 |
+
acc.valid = True
|
| 243 |
+
|
| 244 |
+
def mark_rate_limited(self, acc: Account, cooldown: int | None = None, error_message: str = ""):
|
| 245 |
+
acc.rate_limit_strikes += 1
|
| 246 |
+
base = cooldown if cooldown is not None else settings.RATE_LIMIT_BASE_COOLDOWN
|
| 247 |
+
dynamic = min(settings.RATE_LIMIT_MAX_COOLDOWN, int(base * (2 ** max(0, acc.rate_limit_strikes - 1))))
|
| 248 |
+
dynamic += int(_jitter_seconds())
|
| 249 |
+
acc.rate_limited_until = time.time() + dynamic
|
| 250 |
+
acc.status_code = "rate_limited"
|
| 251 |
+
acc.last_error = error_message or acc.last_error
|
| 252 |
+
if self._sticky_email == acc.email:
|
| 253 |
+
self._sticky_email = None
|
| 254 |
+
log.warning(f"[账号] {acc.email} 已限流冷却 {dynamic} 秒")
|
| 255 |
+
|
| 256 |
+
def status(self):
|
| 257 |
+
available = [a for a in self.accounts if a.is_available()]
|
| 258 |
+
rate_limited = [a for a in self.accounts if a.get_status_code() == "rate_limited"]
|
| 259 |
+
invalid = [a for a in self.accounts if a.get_status_code() not in ("valid", "rate_limited")]
|
| 260 |
+
activation_pending = [a for a in self.accounts if a.get_status_code() == "pending_activation"]
|
| 261 |
+
banned = [a for a in self.accounts if a.get_status_code() == "banned"]
|
| 262 |
+
in_use = sum(a.inflight for a in self.accounts)
|
| 263 |
+
account_min_interval_ms = getattr(settings, "ACCOUNT_MIN_INTERVAL_MS", 0)
|
| 264 |
+
return {
|
| 265 |
+
"total": len(self.accounts),
|
| 266 |
+
"valid": len(available),
|
| 267 |
+
"rate_limited": len(rate_limited),
|
| 268 |
+
"invalid": len(invalid),
|
| 269 |
+
"activation_pending": len(activation_pending),
|
| 270 |
+
"banned": len(banned),
|
| 271 |
+
"in_use": in_use,
|
| 272 |
+
"max_inflight": self.max_inflight,
|
| 273 |
+
"waiting": len(self._waiters),
|
| 274 |
+
"account_min_interval_ms": account_min_interval_ms,
|
| 275 |
+
}
|
backend/core/browser_engine.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import os
|
| 3 |
+
from contextlib import asynccontextmanager
|
| 4 |
+
|
| 5 |
+
_CAMOUFOX_OPTS = {
|
| 6 |
+
"headless": True,
|
| 7 |
+
"humanize": False,
|
| 8 |
+
"i_know_what_im_doing": True,
|
| 9 |
+
"firefox_user_prefs": {
|
| 10 |
+
"layers.acceleration.disabled": True,
|
| 11 |
+
"gfx.webrender.enabled": False,
|
| 12 |
+
"gfx.webrender.all": False,
|
| 13 |
+
"gfx.webrender.software": False,
|
| 14 |
+
"gfx.canvas.azure.backends": "skia",
|
| 15 |
+
"media.hardware-video-decoding.enabled": False,
|
| 16 |
+
},
|
| 17 |
+
}
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@asynccontextmanager
|
| 21 |
+
async def _new_browser():
|
| 22 |
+
from camoufox.async_api import AsyncCamoufox
|
| 23 |
+
|
| 24 |
+
async with AsyncCamoufox(**_CAMOUFOX_OPTS) as browser:
|
| 25 |
+
yield browser
|
| 26 |
+
|
| 27 |
+
|
| 28 |
+
async def ensure_browser_installed():
|
| 29 |
+
import subprocess
|
| 30 |
+
import sys
|
| 31 |
+
|
| 32 |
+
try:
|
| 33 |
+
result = await asyncio.get_event_loop().run_in_executor(
|
| 34 |
+
None,
|
| 35 |
+
lambda: subprocess.run(
|
| 36 |
+
[sys.executable, "-m", "camoufox", "path"],
|
| 37 |
+
capture_output=True,
|
| 38 |
+
text=True,
|
| 39 |
+
timeout=10,
|
| 40 |
+
),
|
| 41 |
+
)
|
| 42 |
+
cache_dir = result.stdout.strip()
|
| 43 |
+
if cache_dir:
|
| 44 |
+
exe_name = "camoufox.exe" if os.name == "nt" else "camoufox"
|
| 45 |
+
exe_path = os.path.join(cache_dir, exe_name)
|
| 46 |
+
if os.path.exists(exe_path):
|
| 47 |
+
return
|
| 48 |
+
except Exception:
|
| 49 |
+
pass
|
| 50 |
+
|
| 51 |
+
loop = asyncio.get_event_loop()
|
| 52 |
+
|
| 53 |
+
def _do_install():
|
| 54 |
+
from camoufox.pkgman import CamoufoxFetcher
|
| 55 |
+
|
| 56 |
+
CamoufoxFetcher().install()
|
| 57 |
+
|
| 58 |
+
await loop.run_in_executor(None, _do_install)
|
backend/core/config.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import json
|
| 3 |
+
from pathlib import Path
|
| 4 |
+
from pydantic_settings import BaseSettings
|
| 5 |
+
from typing import Dict, Set
|
| 6 |
+
|
| 7 |
+
BASE_DIR = Path(__file__).resolve().parent.parent.parent
|
| 8 |
+
DATA_DIR = BASE_DIR / "data"
|
| 9 |
+
|
| 10 |
+
class Settings(BaseSettings):
|
| 11 |
+
# 服务配置
|
| 12 |
+
PORT: int = int(os.getenv("PORT", 8080))
|
| 13 |
+
WORKERS: int = int(os.getenv("WORKERS", 3))
|
| 14 |
+
ADMIN_KEY: str = os.getenv("ADMIN_KEY", "admin")
|
| 15 |
+
|
| 16 |
+
# 并发配置(浏览器仅用于账号注册,不用于对话请求)
|
| 17 |
+
BROWSER_POOL_SIZE: int = int(os.getenv("BROWSER_POOL_SIZE", 1))
|
| 18 |
+
MAX_INFLIGHT_PER_ACCOUNT: int = int(os.getenv("MAX_INFLIGHT", 2))
|
| 19 |
+
BROWSER_STREAM_TIMEOUT_SECONDS: int = int(os.getenv("BROWSER_STREAM_TIMEOUT_SECONDS", 1800))
|
| 20 |
+
|
| 21 |
+
# 容灾与限流
|
| 22 |
+
MAX_RETRIES: int = 3
|
| 23 |
+
RATE_LIMIT_COOLDOWN: int = 600
|
| 24 |
+
ACCOUNT_MIN_INTERVAL_MS: int = int(os.getenv("ACCOUNT_MIN_INTERVAL_MS", 0))
|
| 25 |
+
REQUEST_JITTER_MIN_MS: int = int(os.getenv("REQUEST_JITTER_MIN_MS", 0))
|
| 26 |
+
REQUEST_JITTER_MAX_MS: int = int(os.getenv("REQUEST_JITTER_MAX_MS", 0))
|
| 27 |
+
RATE_LIMIT_BASE_COOLDOWN: int = int(os.getenv("RATE_LIMIT_BASE_COOLDOWN", 600))
|
| 28 |
+
RATE_LIMIT_MAX_COOLDOWN: int = int(os.getenv("RATE_LIMIT_MAX_COOLDOWN", 3600))
|
| 29 |
+
|
| 30 |
+
# 日志
|
| 31 |
+
LOG_LEVEL: str = os.getenv("LOG_LEVEL", "INFO")
|
| 32 |
+
|
| 33 |
+
# 数据文件路径
|
| 34 |
+
ACCOUNTS_FILE: str = os.getenv("ACCOUNTS_FILE", str(DATA_DIR / "accounts.json"))
|
| 35 |
+
USERS_FILE: str = os.getenv("USERS_FILE", str(DATA_DIR / "users.json"))
|
| 36 |
+
CAPTURES_FILE: str = os.getenv("CAPTURES_FILE", str(DATA_DIR / "captures.json"))
|
| 37 |
+
CONFIG_FILE: str = os.getenv("CONFIG_FILE", str(DATA_DIR / "config.json"))
|
| 38 |
+
|
| 39 |
+
# ????? / ????
|
| 40 |
+
CONTEXT_INLINE_MAX_CHARS: int = int(os.getenv("CONTEXT_INLINE_MAX_CHARS", 4000))
|
| 41 |
+
CONTEXT_FORCE_FILE_MAX_CHARS: int = int(os.getenv("CONTEXT_FORCE_FILE_MAX_CHARS", 10000))
|
| 42 |
+
CONTEXT_ATTACHMENT_TTL_SECONDS: int = int(os.getenv("CONTEXT_ATTACHMENT_TTL_SECONDS", 1800))
|
| 43 |
+
CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS: int = int(os.getenv("CONTEXT_UPLOAD_PARSE_TIMEOUT_SECONDS", 60))
|
| 44 |
+
CONTEXT_GENERATED_DIR: str = os.getenv("CONTEXT_GENERATED_DIR", str(DATA_DIR / "context_files"))
|
| 45 |
+
CONTEXT_CACHE_FILE: str = os.getenv("CONTEXT_CACHE_FILE", str(DATA_DIR / "context_cache.json"))
|
| 46 |
+
UPLOADED_FILES_FILE: str = os.getenv("UPLOADED_FILES_FILE", str(DATA_DIR / "uploaded_files.json"))
|
| 47 |
+
CONTEXT_AFFINITY_FILE: str = os.getenv("CONTEXT_AFFINITY_FILE", str(DATA_DIR / "session_affinity.json"))
|
| 48 |
+
CONTEXT_ALLOWED_GENERATED_EXTS: str = os.getenv("CONTEXT_ALLOWED_GENERATED_EXTS", "txt,md,json,log")
|
| 49 |
+
CONTEXT_ALLOWED_USER_EXTS: str = os.getenv("CONTEXT_ALLOWED_USER_EXTS", "txt,md,json,log,xml,yaml,yml,csv,html,css,py,js,ts,java,c,cpp,cs,php,go,rb,sh,zsh,ps1,bat,cmd,pdf,doc,docx,ppt,pptx,xls,xlsx,png,jpg,jpeg,webp,gif,tiff,bmp,svg")
|
| 50 |
+
|
| 51 |
+
class Config:
|
| 52 |
+
env_file = ".env"
|
| 53 |
+
|
| 54 |
+
API_KEYS_FILE = DATA_DIR / "api_keys.json"
|
| 55 |
+
|
| 56 |
+
def load_api_keys() -> set:
|
| 57 |
+
if API_KEYS_FILE.exists():
|
| 58 |
+
try:
|
| 59 |
+
with open(API_KEYS_FILE, "r", encoding="utf-8") as f:
|
| 60 |
+
data = json.load(f)
|
| 61 |
+
return set(data.get("keys", []))
|
| 62 |
+
except Exception:
|
| 63 |
+
pass
|
| 64 |
+
return set()
|
| 65 |
+
|
| 66 |
+
def save_api_keys(keys: set):
|
| 67 |
+
API_KEYS_FILE.parent.mkdir(parents=True, exist_ok=True)
|
| 68 |
+
with open(API_KEYS_FILE, "w", encoding="utf-8") as f:
|
| 69 |
+
json.dump({"keys": list(keys)}, f, indent=2)
|
| 70 |
+
|
| 71 |
+
# 在内存中存储管理的 API Keys
|
| 72 |
+
API_KEYS = load_api_keys()
|
| 73 |
+
|
| 74 |
+
VERSION = "2.0.0"
|
| 75 |
+
|
| 76 |
+
settings = Settings()
|
| 77 |
+
|
| 78 |
+
# 全局映射
|
| 79 |
+
MODEL_MAP = {
|
| 80 |
+
# OpenAI (legacy)
|
| 81 |
+
"gpt-4o": "qwen3.6-plus",
|
| 82 |
+
"gpt-4o-mini": "qwen3.5-flash",
|
| 83 |
+
"gpt-4-turbo": "qwen3.6-plus",
|
| 84 |
+
"gpt-4": "qwen3.6-plus",
|
| 85 |
+
"gpt-4.1": "qwen3.6-plus",
|
| 86 |
+
"gpt-4.1-mini": "qwen3.5-flash",
|
| 87 |
+
"gpt-3.5-turbo": "qwen3.5-flash",
|
| 88 |
+
"gpt-5": "qwen3.7-max",
|
| 89 |
+
"o1": "qwen3.6-plus",
|
| 90 |
+
"o1-mini": "qwen3.5-flash",
|
| 91 |
+
"o3": "qwen3.7-max",
|
| 92 |
+
"o3-mini": "qwen3.5-flash",
|
| 93 |
+
# OpenAI (2026 latest — point to Qwen3.7-Max for agent workloads)
|
| 94 |
+
"gpt-5.5": "qwen3.7-max",
|
| 95 |
+
"gpt-5.5-mini": "qwen3.6-plus",
|
| 96 |
+
"gpt-5-codex": "qwen3.7-max",
|
| 97 |
+
"gpt-5.5-codex": "qwen3.7-max",
|
| 98 |
+
"o4": "qwen3.7-max",
|
| 99 |
+
"o4-mini": "qwen3.6-plus",
|
| 100 |
+
# Anthropic (legacy)
|
| 101 |
+
"claude-opus-4-6": "qwen3.6-plus",
|
| 102 |
+
"claude-sonnet-4-5": "qwen3.6-plus",
|
| 103 |
+
"claude-3-opus": "qwen3.6-plus",
|
| 104 |
+
"claude-3.5-sonnet": "qwen3.6-plus",
|
| 105 |
+
"claude-3-sonnet": "qwen3.6-plus",
|
| 106 |
+
"claude-3-haiku": "qwen3.5-flash",
|
| 107 |
+
# Anthropic (2026 latest — Claude Code default models)
|
| 108 |
+
"claude-opus-4-7": "qwen3.7-max",
|
| 109 |
+
"claude-sonnet-4-6": "qwen3.7-max",
|
| 110 |
+
"claude-haiku-4-5": "qwen3.6-plus",
|
| 111 |
+
# Gemini (legacy)
|
| 112 |
+
"gemini-2.5-pro": "qwen3.6-plus",
|
| 113 |
+
"gemini-2.5-flash": "qwen3.5-flash",
|
| 114 |
+
# Gemini (2026 latest)
|
| 115 |
+
"gemini-3-pro": "qwen3.7-max",
|
| 116 |
+
"gemini-3-flash": "qwen3.6-plus",
|
| 117 |
+
# Qwen aliases
|
| 118 |
+
"qwen": "qwen3.7-max",
|
| 119 |
+
"qwen-max": "qwen3.7-max",
|
| 120 |
+
"qwen-plus": "qwen3.6-plus",
|
| 121 |
+
"qwen-turbo": "qwen3.5-flash",
|
| 122 |
+
"qwen-max-preview": "qwen3.7-max",
|
| 123 |
+
"qwen3.7-max-preview": "qwen3.7-max",
|
| 124 |
+
"qwen3.7-plus": "qwen3.7-plus",
|
| 125 |
+
# Qwen 3.8 (upstream preview)
|
| 126 |
+
"qwen3.8-max-preview": "qwen3.8-max-preview",
|
| 127 |
+
"qwen3.8-max": "qwen3.8-max-preview",
|
| 128 |
+
"qwen3.8": "qwen3.8-max-preview",
|
| 129 |
+
"qwen-3.8": "qwen3.8-max-preview",
|
| 130 |
+
# DeepSeek
|
| 131 |
+
"deepseek-chat": "qwen3.6-plus",
|
| 132 |
+
"deepseek-reasoner": "qwen3.7-max",
|
| 133 |
+
"deepseek-v4": "qwen3.7-max",
|
| 134 |
+
"deepseek-v4-flash": "qwen3.6-plus",
|
| 135 |
+
}
|
| 136 |
+
|
| 137 |
+
def resolve_model(name: str) -> str:
|
| 138 |
+
return MODEL_MAP.get(name, name)
|
backend/core/database.py
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import json
|
| 3 |
+
import logging
|
| 4 |
+
from pathlib import Path
|
| 5 |
+
from typing import Any, Dict, List, Optional
|
| 6 |
+
|
| 7 |
+
log = logging.getLogger("qwen2api.db")
|
| 8 |
+
|
| 9 |
+
class AsyncJsonDB:
|
| 10 |
+
"""带异步读写锁的 JSON 文件存储,防止并发损坏。"""
|
| 11 |
+
def __init__(self, path: str | Path, default_data: Any = None):
|
| 12 |
+
self.path = Path(path)
|
| 13 |
+
self.default_data = default_data if default_data is not None else []
|
| 14 |
+
self._lock = asyncio.Lock()
|
| 15 |
+
self._data: Any = None
|
| 16 |
+
self._init_file()
|
| 17 |
+
|
| 18 |
+
def _init_file(self):
|
| 19 |
+
if not self.path.exists():
|
| 20 |
+
self.path.parent.mkdir(parents=True, exist_ok=True)
|
| 21 |
+
self.path.write_text(json.dumps(self.default_data, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 22 |
+
|
| 23 |
+
async def load(self) -> Any:
|
| 24 |
+
async with self._lock:
|
| 25 |
+
if not self.path.exists():
|
| 26 |
+
self._data = self.default_data
|
| 27 |
+
return self._data
|
| 28 |
+
try:
|
| 29 |
+
# 为了不阻塞事件循环,本应用可使用 asyncio.to_thread 或者直接读,因为文件很小
|
| 30 |
+
content = self.path.read_text(encoding="utf-8")
|
| 31 |
+
self._data = json.loads(content)
|
| 32 |
+
except Exception as e:
|
| 33 |
+
log.error(f"Failed to load JSON from {self.path}: {e}")
|
| 34 |
+
self._data = self.default_data
|
| 35 |
+
return self._data
|
| 36 |
+
|
| 37 |
+
async def save(self, data: Any):
|
| 38 |
+
async with self._lock:
|
| 39 |
+
self._data = data
|
| 40 |
+
try:
|
| 41 |
+
self.path.write_text(json.dumps(self._data, indent=2, ensure_ascii=False), encoding="utf-8")
|
| 42 |
+
except Exception as e:
|
| 43 |
+
log.error(f"Failed to save JSON to {self.path}: {e}")
|
| 44 |
+
|
| 45 |
+
async def get(self) -> Any:
|
| 46 |
+
if self._data is None:
|
| 47 |
+
return await self.load()
|
| 48 |
+
return self._data
|
backend/core/httpx_engine.py
ADDED
|
@@ -0,0 +1,135 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
httpx_engine.py — 用 curl_cffi 直连 Qwen API(Chrome TLS 指纹)
|
| 3 |
+
优点:TLS 指纹与真实 Chrome 一致,无编码问题,支持流式早期中止
|
| 4 |
+
优化:使用全局连接池,避免频繁 TLS 握手
|
| 5 |
+
"""
|
| 6 |
+
|
| 7 |
+
import asyncio
|
| 8 |
+
import json
|
| 9 |
+
import logging
|
| 10 |
+
from curl_cffi.requests import AsyncSession
|
| 11 |
+
|
| 12 |
+
log = logging.getLogger("qwen2api.httpx_engine")
|
| 13 |
+
|
| 14 |
+
BASE_URL = "https://chat.qwen.ai"
|
| 15 |
+
|
| 16 |
+
_HEADERS = {
|
| 17 |
+
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/124.0.0.0 Safari/537.36",
|
| 18 |
+
"Accept": "application/json, text/plain, */*",
|
| 19 |
+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
| 20 |
+
"Referer": "https://chat.qwen.ai/",
|
| 21 |
+
"Origin": "https://chat.qwen.ai",
|
| 22 |
+
"sec-ch-ua": '"Chromium";v="124", "Google Chrome";v="124", "Not-A.Brand";v="99"',
|
| 23 |
+
"sec-ch-ua-mobile": "?0",
|
| 24 |
+
"sec-ch-ua-platform": '"Windows"',
|
| 25 |
+
"sec-fetch-dest": "empty",
|
| 26 |
+
"sec-fetch-mode": "cors",
|
| 27 |
+
"sec-fetch-site": "same-origin",
|
| 28 |
+
}
|
| 29 |
+
|
| 30 |
+
_IMPERSONATE = "chrome124"
|
| 31 |
+
|
| 32 |
+
# ✅ 全局连接池(避免频繁 TLS 握手)
|
| 33 |
+
_global_session: AsyncSession = None
|
| 34 |
+
_session_lock: asyncio.Lock = None
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
async def _get_global_session() -> AsyncSession:
|
| 38 |
+
"""获取全局 AsyncSession"""
|
| 39 |
+
global _global_session, _session_lock
|
| 40 |
+
|
| 41 |
+
if _session_lock is None:
|
| 42 |
+
_session_lock = asyncio.Lock()
|
| 43 |
+
|
| 44 |
+
if _global_session is not None:
|
| 45 |
+
return _global_session
|
| 46 |
+
|
| 47 |
+
async with _session_lock:
|
| 48 |
+
if _global_session is not None:
|
| 49 |
+
return _global_session
|
| 50 |
+
|
| 51 |
+
_global_session = AsyncSession(impersonate=_IMPERSONATE, timeout=30)
|
| 52 |
+
log.info("[HttpxEngine] ✅ 全局连接池已初始化")
|
| 53 |
+
return _global_session
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
async def _close_global_session():
|
| 57 |
+
"""关闭全局 session"""
|
| 58 |
+
global _global_session
|
| 59 |
+
if _global_session:
|
| 60 |
+
try:
|
| 61 |
+
await _global_session.close()
|
| 62 |
+
log.info("[HttpxEngine] ✅ 全局连接池已关闭")
|
| 63 |
+
except Exception as e:
|
| 64 |
+
log.error(f"[HttpxEngine] 关闭连接池失败: {e}")
|
| 65 |
+
finally:
|
| 66 |
+
_global_session = None
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class HttpxEngine:
|
| 70 |
+
"""Direct curl_cffi engine — Chrome TLS fingerprint, same interface as BrowserEngine."""
|
| 71 |
+
|
| 72 |
+
def __init__(self, pool_size: int = 3, base_url: str = BASE_URL):
|
| 73 |
+
self.base_url = base_url
|
| 74 |
+
self._started = False
|
| 75 |
+
self._ready = asyncio.Event()
|
| 76 |
+
|
| 77 |
+
async def start(self):
|
| 78 |
+
# ✅ 初始化全局连接池
|
| 79 |
+
await _get_global_session()
|
| 80 |
+
self._started = True
|
| 81 |
+
self._ready.set()
|
| 82 |
+
log.info("[HttpxEngine] 已启动(curl_cffi Chrome指纹直连模式 + 全局连接池)")
|
| 83 |
+
|
| 84 |
+
async def stop(self):
|
| 85 |
+
self._started = False
|
| 86 |
+
# ✅ 关闭全局连接池
|
| 87 |
+
await _close_global_session()
|
| 88 |
+
log.info("[HttpxEngine] 已停止")
|
| 89 |
+
|
| 90 |
+
def _auth_headers(self, token: str) -> dict:
|
| 91 |
+
return {**_HEADERS, "Authorization": f"Bearer {token}"}
|
| 92 |
+
|
| 93 |
+
async def api_call(self, method: str, path: str, token: str, body: dict = None) -> dict:
|
| 94 |
+
# ✅ 改进:使用全局 session 而不是创建新的
|
| 95 |
+
url = self.base_url + path
|
| 96 |
+
headers = {**self._auth_headers(token), "Content-Type": "application/json"}
|
| 97 |
+
data = json.dumps(body, ensure_ascii=False).encode() if body else None
|
| 98 |
+
try:
|
| 99 |
+
session = await _get_global_session()
|
| 100 |
+
resp = await session.request(method, url, headers=headers, data=data)
|
| 101 |
+
return {"status": resp.status_code, "body": resp.text}
|
| 102 |
+
except Exception as e:
|
| 103 |
+
log.error(f"[HttpxEngine] api_call error: {e}")
|
| 104 |
+
return {"status": 0, "body": str(e)}
|
| 105 |
+
|
| 106 |
+
async def fetch_chat(self, token: str, chat_id: str, payload: dict, buffered: bool = False):
|
| 107 |
+
"""Stream Qwen SSE via curl_cffi with Chrome TLS fingerprint (with global connection pool)."""
|
| 108 |
+
# ✅ 改进:使用全局 session 而不是创建新的
|
| 109 |
+
url = self.base_url + f"/api/v2/chat/completions?chat_id={chat_id}"
|
| 110 |
+
headers = {
|
| 111 |
+
**self._auth_headers(token),
|
| 112 |
+
"Content-Type": "application/json",
|
| 113 |
+
"Accept": "text/event-stream",
|
| 114 |
+
}
|
| 115 |
+
body_bytes = json.dumps(payload, ensure_ascii=False).encode()
|
| 116 |
+
|
| 117 |
+
try:
|
| 118 |
+
session = await _get_global_session()
|
| 119 |
+
async with session.stream("POST", url, headers=headers, data=body_bytes) as resp:
|
| 120 |
+
if resp.status_code != 200:
|
| 121 |
+
body_chunks = []
|
| 122 |
+
async for chunk in resp.aiter_content():
|
| 123 |
+
body_chunks.append(chunk)
|
| 124 |
+
body_text = b"".join(body_chunks).decode(errors="replace")[:2000]
|
| 125 |
+
yield {"status": resp.status_code, "body": body_text}
|
| 126 |
+
return
|
| 127 |
+
|
| 128 |
+
async for chunk in resp.aiter_content():
|
| 129 |
+
decoded = chunk.decode("utf-8", errors="replace")
|
| 130 |
+
yield {"status": "streamed", "chunk": decoded}
|
| 131 |
+
|
| 132 |
+
except Exception as e:
|
| 133 |
+
log.error(f"[HttpxEngine] fetch_chat error: {e}")
|
| 134 |
+
yield {"status": 0, "body": str(e)}
|
| 135 |
+
|
backend/core/hybrid_engine.py
ADDED
|
@@ -0,0 +1,122 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
hybrid_engine.py — mix browser stability with httpx speed.
|
| 3 |
+
Phase 1 policy:
|
| 4 |
+
- api_call: httpx first, browser fallback on failures
|
| 5 |
+
- fetch_chat: browser first (real browser TLS/env), httpx fallback on browser failures
|
| 6 |
+
"""
|
| 7 |
+
|
| 8 |
+
import logging
|
| 9 |
+
|
| 10 |
+
log = logging.getLogger("qwen2api.hybrid_engine")
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
class HybridEngine:
|
| 14 |
+
def __init__(self, browser_engine, httpx_engine):
|
| 15 |
+
self.browser_engine = browser_engine
|
| 16 |
+
self.httpx_engine = httpx_engine
|
| 17 |
+
self._started = False
|
| 18 |
+
self.base_url = getattr(browser_engine, "base_url", getattr(httpx_engine, "base_url", "https://chat.qwen.ai"))
|
| 19 |
+
self.pool_size = getattr(browser_engine, "pool_size", 0)
|
| 20 |
+
self._pages = getattr(browser_engine, "_pages", None)
|
| 21 |
+
|
| 22 |
+
async def start(self):
|
| 23 |
+
log.info("[HybridEngine] 启动开始:先启动 httpx 引擎")
|
| 24 |
+
await self.httpx_engine.start()
|
| 25 |
+
log.info("[HybridEngine] 第一步完成:httpx 已启动,继续启动浏览器引擎")
|
| 26 |
+
await self.browser_engine.start()
|
| 27 |
+
self._started = bool(getattr(self.httpx_engine, "_started", False) and getattr(self.browser_engine, "_started", False))
|
| 28 |
+
log.info(f"[HybridEngine] 已启动:api_call=httpx优先,fetch_chat=browser优先,started={self._started} browser_started={getattr(self.browser_engine, '_started', False)} httpx_started={getattr(self.httpx_engine, '_started', False)}")
|
| 29 |
+
|
| 30 |
+
async def stop(self):
|
| 31 |
+
try:
|
| 32 |
+
await self.httpx_engine.stop()
|
| 33 |
+
finally:
|
| 34 |
+
await self.browser_engine.stop()
|
| 35 |
+
self._started = False
|
| 36 |
+
log.info("[HybridEngine] 已停止")
|
| 37 |
+
|
| 38 |
+
async def api_call(self, method: str, path: str, token: str, body: dict = None) -> dict:
|
| 39 |
+
log.info(f"[HybridEngine] api_call 路由:优先走 httpx,method={method} path={path}")
|
| 40 |
+
result = await self.httpx_engine.api_call(method, path, token, body)
|
| 41 |
+
status = result.get("status")
|
| 42 |
+
body_text = (result.get("body") or "").lower()
|
| 43 |
+
should_fallback = (
|
| 44 |
+
status == 0
|
| 45 |
+
or status in (401, 403, 429)
|
| 46 |
+
or "waf" in body_text
|
| 47 |
+
or "<!doctype" in body_text
|
| 48 |
+
or "forbidden" in body_text
|
| 49 |
+
or "unauthorized" in body_text
|
| 50 |
+
)
|
| 51 |
+
if should_fallback:
|
| 52 |
+
preview = (result.get("body") or "")[:160].replace("\n", "\\n")
|
| 53 |
+
log.warning(f"[HybridEngine] api_call 回退到 browser,method={method} path={path} status={status} body_preview={preview!r}")
|
| 54 |
+
return await self.browser_engine.api_call(method, path, token, body)
|
| 55 |
+
log.info(f"[HybridEngine] api_call 实际由 httpx 完成,method={method} path={path} status={status}")
|
| 56 |
+
return result
|
| 57 |
+
|
| 58 |
+
async def fetch_chat(self, token: str, chat_id: str, payload: dict, buffered: bool = False):
|
| 59 |
+
log.info(f"[HybridEngine] fetch_chat 路由:优先走 browser,chat_id={chat_id} buffered={buffered}")
|
| 60 |
+
saw_success = False
|
| 61 |
+
browser_error = None
|
| 62 |
+
try:
|
| 63 |
+
async for item in self.browser_engine.fetch_chat(token, chat_id, payload, buffered=buffered):
|
| 64 |
+
status = item.get("status")
|
| 65 |
+
if status in ("streamed", 200):
|
| 66 |
+
saw_success = True
|
| 67 |
+
yield item
|
| 68 |
+
continue
|
| 69 |
+
# 浏览器返回错误,判断是否需要回退
|
| 70 |
+
body_text = (item.get("body") or "").lower()
|
| 71 |
+
is_hard_failure = (
|
| 72 |
+
status in (401, 403, 429)
|
| 73 |
+
or "waf" in body_text
|
| 74 |
+
or "<!doctype" in body_text
|
| 75 |
+
or "forbidden" in body_text
|
| 76 |
+
or "unauthorized" in body_text
|
| 77 |
+
)
|
| 78 |
+
if is_hard_failure and not saw_success:
|
| 79 |
+
browser_error = item
|
| 80 |
+
break
|
| 81 |
+
# 浏览器引擎自身错误(evaluate失败等),也回退
|
| 82 |
+
if status == 0 and not saw_success:
|
| 83 |
+
browser_error = item
|
| 84 |
+
break
|
| 85 |
+
yield item
|
| 86 |
+
if browser_error is None:
|
| 87 |
+
return
|
| 88 |
+
except Exception as e:
|
| 89 |
+
if saw_success:
|
| 90 |
+
return
|
| 91 |
+
browser_error = {"status": 0, "body": str(e)}
|
| 92 |
+
|
| 93 |
+
preview = ((browser_error.get("body") or "")[:160]).replace("\n", "\\n") if isinstance(browser_error, dict) else str(browser_error)[:160]
|
| 94 |
+
log.warning(
|
| 95 |
+
f"[HybridEngine] fetch_chat browser 失败,回退到 httpx:chat_id={chat_id} "
|
| 96 |
+
f"status={browser_error.get('status') if isinstance(browser_error, dict) else 'unknown'} "
|
| 97 |
+
f"body_preview={preview!r}"
|
| 98 |
+
)
|
| 99 |
+
async for item in self.httpx_engine.fetch_chat(token, chat_id, payload, buffered=buffered):
|
| 100 |
+
yield item
|
| 101 |
+
|
| 102 |
+
def status(self) -> dict:
|
| 103 |
+
free_pages = 0
|
| 104 |
+
queue = 0
|
| 105 |
+
if self._pages is not None:
|
| 106 |
+
try:
|
| 107 |
+
free_pages = self._pages.qsize()
|
| 108 |
+
queue = max(0, self.pool_size - free_pages)
|
| 109 |
+
except Exception:
|
| 110 |
+
free_pages = 0
|
| 111 |
+
queue = 0
|
| 112 |
+
return {
|
| 113 |
+
"started": self._started,
|
| 114 |
+
"mode": "hybrid",
|
| 115 |
+
"stream_via": "browser_first",
|
| 116 |
+
"api_via": "httpx_first",
|
| 117 |
+
"browser_started": getattr(self.browser_engine, "_started", False),
|
| 118 |
+
"httpx_started": getattr(self.httpx_engine, "_started", False),
|
| 119 |
+
"pool_size": self.pool_size,
|
| 120 |
+
"free_pages": free_pages,
|
| 121 |
+
"queue": queue,
|
| 122 |
+
}
|
backend/core/log_filter.py
ADDED
|
@@ -0,0 +1,134 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""日志过滤器 - 精简和中文化日志输出"""
|
| 2 |
+
import logging
|
| 3 |
+
import re
|
| 4 |
+
|
| 5 |
+
|
| 6 |
+
class SimplifiedLogFilter(logging.Filter):
|
| 7 |
+
"""精简日志过滤器 - 移除冗余信息"""
|
| 8 |
+
|
| 9 |
+
# 需要完全过滤的日志模式
|
| 10 |
+
SKIP_PATTERNS = [
|
| 11 |
+
r"HTTP Request: POST https://chat\.qwen\.ai",
|
| 12 |
+
r"HTTP Request: GET https://chat\.qwen\.ai",
|
| 13 |
+
r"HTTP Request: DELETE https://chat\.qwen\.ai",
|
| 14 |
+
r"\[ToolParse\].*原始回复",
|
| 15 |
+
r"prompt preview \(first \d+ chars\)",
|
| 16 |
+
r"feature_config:",
|
| 17 |
+
r"prompt contains ##TOOL_CALL##",
|
| 18 |
+
]
|
| 19 |
+
|
| 20 |
+
# 需要简化的日志模式(保留但精简)
|
| 21 |
+
SIMPLIFY_PATTERNS = {
|
| 22 |
+
r"\[SessionPlan\] surface=\S+ enabled=(\S+) reuse_chat=(\S+) reason=(\S+).*":
|
| 23 |
+
r"会话计划: 启用=\1 复用=\2 原因=\3",
|
| 24 |
+
|
| 25 |
+
r"\[Executor\] acquired account=(\S+) model=(\S+) attempt=(\d+)":
|
| 26 |
+
r"获取账号: \1 模型=\2 尝试=\3",
|
| 27 |
+
|
| 28 |
+
r"\[Executor\] created chat_id=(\S+) account=(\S+)":
|
| 29 |
+
r"创建会话: \1 账号=\2",
|
| 30 |
+
|
| 31 |
+
r"\[Executor\] stream start chat_id=(\S+) model=(\S+)":
|
| 32 |
+
r"开始流式: 会话=\1 模型=\2",
|
| 33 |
+
|
| 34 |
+
r"\[Executor\] stream finish chat_id=(\S+) total=([\d.]+)s":
|
| 35 |
+
r"完成流式: 会话=\1 耗时=\2秒",
|
| 36 |
+
|
| 37 |
+
r"\[Executor\] first parsed event after ([\d.]+)s chat_id=(\S+)":
|
| 38 |
+
r"首次响应: \1秒 会话=\2",
|
| 39 |
+
|
| 40 |
+
r"\[Collect\] ✓ Tool Sieve 刷新检测到工具调用: tools=\[([^\]]+)\]":
|
| 41 |
+
r"检测到工具: \1",
|
| 42 |
+
|
| 43 |
+
r"\[Collect\] finalize reason=(\S+) chat_id=(\S+) tool_calls=(\d+)":
|
| 44 |
+
r"完成收集: 原因=\1 工具数=\3",
|
| 45 |
+
|
| 46 |
+
r"\[ANT\] model=(\S+), stream=(\S+), tool_enabled=(\S+)":
|
| 47 |
+
r"请求配置: 模型=\1 流式=\2 工具=\3",
|
| 48 |
+
}
|
| 49 |
+
|
| 50 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 51 |
+
msg = record.getMessage()
|
| 52 |
+
|
| 53 |
+
# 检查是否需要完全过滤
|
| 54 |
+
for pattern in self.SKIP_PATTERNS:
|
| 55 |
+
if re.search(pattern, msg):
|
| 56 |
+
return False
|
| 57 |
+
|
| 58 |
+
# 检查是否需要简化
|
| 59 |
+
for pattern, replacement in self.SIMPLIFY_PATTERNS.items():
|
| 60 |
+
match = re.search(pattern, msg)
|
| 61 |
+
if match:
|
| 62 |
+
record.msg = re.sub(pattern, replacement, msg)
|
| 63 |
+
record.args = ()
|
| 64 |
+
break
|
| 65 |
+
|
| 66 |
+
return True
|
| 67 |
+
|
| 68 |
+
|
| 69 |
+
class ChineseLogFilter(logging.Filter):
|
| 70 |
+
"""中文化日志过滤器 - 将英文日志转换为中文"""
|
| 71 |
+
|
| 72 |
+
TRANSLATIONS = {
|
| 73 |
+
# 启动/关闭
|
| 74 |
+
"Starting": "启动中",
|
| 75 |
+
"Shutting down": "关闭中",
|
| 76 |
+
"Startup complete": "启动完成",
|
| 77 |
+
|
| 78 |
+
# 账号相关
|
| 79 |
+
"Account": "账号",
|
| 80 |
+
"account": "账号",
|
| 81 |
+
"token": "令牌",
|
| 82 |
+
"Token": "令牌",
|
| 83 |
+
|
| 84 |
+
# 请求相关
|
| 85 |
+
"Request": "请求",
|
| 86 |
+
"request": "请求",
|
| 87 |
+
"Response": "响应",
|
| 88 |
+
"response": "响应",
|
| 89 |
+
|
| 90 |
+
# 模型相关
|
| 91 |
+
"model": "模型",
|
| 92 |
+
"Model": "模型",
|
| 93 |
+
|
| 94 |
+
# 工具相关
|
| 95 |
+
"tool": "工具",
|
| 96 |
+
"Tool": "工具",
|
| 97 |
+
"tools": "工具",
|
| 98 |
+
"Tools": "工具",
|
| 99 |
+
|
| 100 |
+
# 状态
|
| 101 |
+
"success": "成功",
|
| 102 |
+
"Success": "成功",
|
| 103 |
+
"failed": "失败",
|
| 104 |
+
"Failed": "失败",
|
| 105 |
+
"error": "错误",
|
| 106 |
+
"Error": "错误",
|
| 107 |
+
"warning": "警告",
|
| 108 |
+
"Warning": "警告",
|
| 109 |
+
|
| 110 |
+
# 动作
|
| 111 |
+
"created": "已创建",
|
| 112 |
+
"Created": "已创建",
|
| 113 |
+
"deleted": "已删除",
|
| 114 |
+
"Deleted": "已删除",
|
| 115 |
+
"updated": "已更新",
|
| 116 |
+
"Updated": "已更新",
|
| 117 |
+
}
|
| 118 |
+
|
| 119 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 120 |
+
msg = record.getMessage()
|
| 121 |
+
|
| 122 |
+
# 简单替换(仅替换独立单词)
|
| 123 |
+
for en, zh in self.TRANSLATIONS.items():
|
| 124 |
+
msg = re.sub(rf'\b{en}\b', zh, msg)
|
| 125 |
+
|
| 126 |
+
record.msg = msg
|
| 127 |
+
record.args = ()
|
| 128 |
+
return True
|
| 129 |
+
|
| 130 |
+
|
| 131 |
+
def apply_log_filters(logger: logging.Logger) -> None:
|
| 132 |
+
"""应用日志过滤器到指定 logger"""
|
| 133 |
+
logger.addFilter(SimplifiedLogFilter())
|
| 134 |
+
# logger.addFilter(ChineseLogFilter()) # 可选:启用中文化
|
backend/core/request_logging.py
ADDED
|
@@ -0,0 +1,98 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import contextvars
|
| 2 |
+
import logging
|
| 3 |
+
import uuid
|
| 4 |
+
from contextlib import contextmanager
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
_REQUEST_CONTEXT: contextvars.ContextVar[dict[str, Any]] = contextvars.ContextVar(
|
| 8 |
+
"request_context", default={}
|
| 9 |
+
)
|
| 10 |
+
|
| 11 |
+
_REQUEST_DEFAULTS: dict[str, Any] = {
|
| 12 |
+
"req_id": "-",
|
| 13 |
+
"surface": "-",
|
| 14 |
+
"requested_model": "-",
|
| 15 |
+
"resolved_model": "-",
|
| 16 |
+
"chat_id": "-",
|
| 17 |
+
"stream_attempt": "-",
|
| 18 |
+
"upstream_attempt": "-",
|
| 19 |
+
}
|
| 20 |
+
|
| 21 |
+
_LOG_FORMAT = (
|
| 22 |
+
"%(asctime)s [%(levelname)s] %(message)s"
|
| 23 |
+
)
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class RequestContextFilter(logging.Filter):
|
| 27 |
+
def filter(self, record: logging.LogRecord) -> bool:
|
| 28 |
+
ctx = get_request_context()
|
| 29 |
+
for key, default in _REQUEST_DEFAULTS.items():
|
| 30 |
+
setattr(record, key, ctx.get(key, default))
|
| 31 |
+
return True
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
request_context_filter = RequestContextFilter()
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
class SafeRequestFormatter(logging.Formatter):
|
| 38 |
+
def format(self, record: logging.LogRecord) -> str:
|
| 39 |
+
for key, default in _REQUEST_DEFAULTS.items():
|
| 40 |
+
if not hasattr(record, key):
|
| 41 |
+
setattr(record, key, default)
|
| 42 |
+
return super().format(record)
|
| 43 |
+
|
| 44 |
+
|
| 45 |
+
def configure_logging(level: int = logging.INFO) -> None:
|
| 46 |
+
root = logging.getLogger()
|
| 47 |
+
root.setLevel(level)
|
| 48 |
+
|
| 49 |
+
# 应用精简日志过滤器
|
| 50 |
+
try:
|
| 51 |
+
from backend.core.log_filter import SimplifiedLogFilter
|
| 52 |
+
if not any(isinstance(f, SimplifiedLogFilter) for f in root.filters):
|
| 53 |
+
root.addFilter(SimplifiedLogFilter())
|
| 54 |
+
except ImportError:
|
| 55 |
+
pass
|
| 56 |
+
|
| 57 |
+
formatter = SafeRequestFormatter(_LOG_FORMAT)
|
| 58 |
+
|
| 59 |
+
if not root.handlers:
|
| 60 |
+
handler = logging.StreamHandler()
|
| 61 |
+
handler.setLevel(level)
|
| 62 |
+
handler.setFormatter(formatter)
|
| 63 |
+
root.addHandler(handler)
|
| 64 |
+
return
|
| 65 |
+
|
| 66 |
+
for handler in root.handlers:
|
| 67 |
+
handler.setLevel(level)
|
| 68 |
+
handler.setFormatter(formatter)
|
| 69 |
+
|
| 70 |
+
|
| 71 |
+
def new_request_id() -> str:
|
| 72 |
+
return uuid.uuid4().hex[:8]
|
| 73 |
+
|
| 74 |
+
|
| 75 |
+
def get_request_context() -> dict[str, Any]:
|
| 76 |
+
ctx = dict(_REQUEST_DEFAULTS)
|
| 77 |
+
ctx.update(_REQUEST_CONTEXT.get({}))
|
| 78 |
+
return ctx
|
| 79 |
+
|
| 80 |
+
|
| 81 |
+
def update_request_context(**kwargs: Any) -> dict[str, Any]:
|
| 82 |
+
ctx = get_request_context()
|
| 83 |
+
for key, value in kwargs.items():
|
| 84 |
+
if value is not None:
|
| 85 |
+
ctx[key] = value
|
| 86 |
+
_REQUEST_CONTEXT.set(ctx)
|
| 87 |
+
return ctx
|
| 88 |
+
|
| 89 |
+
|
| 90 |
+
@contextmanager
|
| 91 |
+
def request_context(**kwargs: Any):
|
| 92 |
+
merged = get_request_context()
|
| 93 |
+
merged.update({k: v for k, v in kwargs.items() if v is not None})
|
| 94 |
+
token = _REQUEST_CONTEXT.set(merged)
|
| 95 |
+
try:
|
| 96 |
+
yield _REQUEST_CONTEXT.get({})
|
| 97 |
+
finally:
|
| 98 |
+
_REQUEST_CONTEXT.reset(token)
|
backend/core/session_affinity.py
ADDED
|
@@ -0,0 +1,153 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from backend.core.database import AsyncJsonDB
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(slots=True)
|
| 11 |
+
class SessionAffinityRecord:
|
| 12 |
+
session_key: str
|
| 13 |
+
surface: str
|
| 14 |
+
account_email: str
|
| 15 |
+
uploaded_files: list[dict[str, Any]] = field(default_factory=list)
|
| 16 |
+
chat_id: str | None = None
|
| 17 |
+
message_hashes: list[str] = field(default_factory=list)
|
| 18 |
+
updated_at: float = 0.0
|
| 19 |
+
expires_at: float = 0.0
|
| 20 |
+
|
| 21 |
+
def to_dict(self) -> dict[str, Any]:
|
| 22 |
+
return {
|
| 23 |
+
"session_key": self.session_key,
|
| 24 |
+
"surface": self.surface,
|
| 25 |
+
"account_email": self.account_email,
|
| 26 |
+
"uploaded_files": self.uploaded_files,
|
| 27 |
+
"chat_id": self.chat_id,
|
| 28 |
+
"message_hashes": self.message_hashes,
|
| 29 |
+
"updated_at": self.updated_at,
|
| 30 |
+
"expires_at": self.expires_at,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class SessionAffinityStore:
|
| 35 |
+
def __init__(self, db: AsyncJsonDB):
|
| 36 |
+
self.db = db
|
| 37 |
+
self.records: dict[str, SessionAffinityRecord] = {}
|
| 38 |
+
|
| 39 |
+
@staticmethod
|
| 40 |
+
def _from_item(item: dict[str, Any]) -> SessionAffinityRecord | None:
|
| 41 |
+
if not isinstance(item, dict) or not item.get("session_key"):
|
| 42 |
+
return None
|
| 43 |
+
return SessionAffinityRecord(
|
| 44 |
+
session_key=str(item.get("session_key") or ""),
|
| 45 |
+
surface=str(item.get("surface") or ""),
|
| 46 |
+
account_email=str(item.get("account_email") or ""),
|
| 47 |
+
uploaded_files=list(item.get("uploaded_files") or []),
|
| 48 |
+
chat_id=(str(item.get("chat_id")) if item.get("chat_id") else None),
|
| 49 |
+
message_hashes=[str(v) for v in (item.get("message_hashes") or []) if str(v)],
|
| 50 |
+
updated_at=float(item.get("updated_at") or 0.0),
|
| 51 |
+
expires_at=float(item.get("expires_at") or 0.0),
|
| 52 |
+
)
|
| 53 |
+
|
| 54 |
+
async def load(self):
|
| 55 |
+
data = await self.db.load()
|
| 56 |
+
self.records = {}
|
| 57 |
+
if isinstance(data, list):
|
| 58 |
+
for item in data:
|
| 59 |
+
rec = self._from_item(item)
|
| 60 |
+
if rec is None:
|
| 61 |
+
continue
|
| 62 |
+
self.records[rec.session_key] = rec
|
| 63 |
+
|
| 64 |
+
async def save(self):
|
| 65 |
+
await self.db.save([record.to_dict() for record in self.records.values()])
|
| 66 |
+
|
| 67 |
+
async def get(self, session_key: str) -> SessionAffinityRecord | None:
|
| 68 |
+
if not self.records:
|
| 69 |
+
await self.load()
|
| 70 |
+
record = self.records.get(session_key)
|
| 71 |
+
if record and record.expires_at and record.expires_at < time.time():
|
| 72 |
+
self.records.pop(session_key, None)
|
| 73 |
+
await self.save()
|
| 74 |
+
return None
|
| 75 |
+
return record
|
| 76 |
+
|
| 77 |
+
async def bind_account(self, session_key: str, surface: str, account_email: str, ttl_seconds: int) -> SessionAffinityRecord:
|
| 78 |
+
now = time.time()
|
| 79 |
+
record = self.records.get(session_key)
|
| 80 |
+
if record is None:
|
| 81 |
+
record = SessionAffinityRecord(session_key=session_key, surface=surface, account_email=account_email)
|
| 82 |
+
record.surface = surface
|
| 83 |
+
record.account_email = account_email
|
| 84 |
+
record.updated_at = now
|
| 85 |
+
record.expires_at = now + max(60, ttl_seconds)
|
| 86 |
+
self.records[session_key] = record
|
| 87 |
+
await self.save()
|
| 88 |
+
return record
|
| 89 |
+
|
| 90 |
+
async def bind_chat(
|
| 91 |
+
self,
|
| 92 |
+
session_key: str,
|
| 93 |
+
*,
|
| 94 |
+
surface: str,
|
| 95 |
+
account_email: str,
|
| 96 |
+
chat_id: str,
|
| 97 |
+
message_hashes: list[str],
|
| 98 |
+
ttl_seconds: int,
|
| 99 |
+
) -> SessionAffinityRecord:
|
| 100 |
+
now = time.time()
|
| 101 |
+
record = self.records.get(session_key)
|
| 102 |
+
if record is None:
|
| 103 |
+
record = SessionAffinityRecord(session_key=session_key, surface=surface, account_email=account_email)
|
| 104 |
+
record.surface = surface
|
| 105 |
+
record.account_email = account_email
|
| 106 |
+
record.chat_id = chat_id
|
| 107 |
+
record.message_hashes = list(message_hashes)
|
| 108 |
+
record.updated_at = now
|
| 109 |
+
record.expires_at = now + max(60, ttl_seconds)
|
| 110 |
+
self.records[session_key] = record
|
| 111 |
+
await self.save()
|
| 112 |
+
return record
|
| 113 |
+
|
| 114 |
+
async def clear_chat(self, session_key: str) -> None:
|
| 115 |
+
record = await self.get(session_key)
|
| 116 |
+
if record is None:
|
| 117 |
+
return
|
| 118 |
+
record.chat_id = None
|
| 119 |
+
record.message_hashes = []
|
| 120 |
+
record.updated_at = time.time()
|
| 121 |
+
self.records[session_key] = record
|
| 122 |
+
await self.save()
|
| 123 |
+
|
| 124 |
+
async def add_uploaded_file(self, session_key: str, file_meta: dict[str, Any]) -> None:
|
| 125 |
+
record = await self.get(session_key)
|
| 126 |
+
if record is None:
|
| 127 |
+
return
|
| 128 |
+
record.uploaded_files.append(file_meta)
|
| 129 |
+
record.updated_at = time.time()
|
| 130 |
+
self.records[session_key] = record
|
| 131 |
+
await self.save()
|
| 132 |
+
|
| 133 |
+
async def clear(self, session_key: str) -> None:
|
| 134 |
+
self.records.pop(session_key, None)
|
| 135 |
+
await self.save()
|
| 136 |
+
|
| 137 |
+
def active_chat_ids(self) -> set[str]:
|
| 138 |
+
now = time.time()
|
| 139 |
+
return {
|
| 140 |
+
record.chat_id
|
| 141 |
+
for record in self.records.values()
|
| 142 |
+
if record.chat_id and (not record.expires_at or record.expires_at >= now)
|
| 143 |
+
}
|
| 144 |
+
|
| 145 |
+
async def cleanup_expired(self) -> list[SessionAffinityRecord]:
|
| 146 |
+
now = time.time()
|
| 147 |
+
expired_keys = [key for key, record in self.records.items() if record.expires_at and record.expires_at < now]
|
| 148 |
+
expired_records = [self.records[key] for key in expired_keys]
|
| 149 |
+
for key in expired_keys:
|
| 150 |
+
self.records.pop(key, None)
|
| 151 |
+
if expired_keys:
|
| 152 |
+
await self.save()
|
| 153 |
+
return expired_records
|
backend/core/session_lock.py
ADDED
|
@@ -0,0 +1,40 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
from contextlib import asynccontextmanager
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
class SessionLockRegistry:
|
| 8 |
+
def __init__(self):
|
| 9 |
+
self._locks: dict[str, asyncio.Lock] = {}
|
| 10 |
+
self._refs: dict[str, int] = {}
|
| 11 |
+
self._guard = asyncio.Lock()
|
| 12 |
+
|
| 13 |
+
async def _get_lock(self, session_key: str) -> asyncio.Lock:
|
| 14 |
+
async with self._guard:
|
| 15 |
+
lock = self._locks.get(session_key)
|
| 16 |
+
if lock is None:
|
| 17 |
+
lock = asyncio.Lock()
|
| 18 |
+
self._locks[session_key] = lock
|
| 19 |
+
self._refs[session_key] = 0
|
| 20 |
+
self._refs[session_key] = self._refs.get(session_key, 0) + 1
|
| 21 |
+
return lock
|
| 22 |
+
|
| 23 |
+
async def _release_ref(self, session_key: str) -> None:
|
| 24 |
+
async with self._guard:
|
| 25 |
+
if session_key not in self._refs:
|
| 26 |
+
return
|
| 27 |
+
self._refs[session_key] = max(0, self._refs[session_key] - 1)
|
| 28 |
+
if self._refs[session_key] == 0:
|
| 29 |
+
self._refs.pop(session_key, None)
|
| 30 |
+
self._locks.pop(session_key, None)
|
| 31 |
+
|
| 32 |
+
@asynccontextmanager
|
| 33 |
+
async def hold(self, session_key: str):
|
| 34 |
+
lock = await self._get_lock(session_key)
|
| 35 |
+
await lock.acquire()
|
| 36 |
+
try:
|
| 37 |
+
yield
|
| 38 |
+
finally:
|
| 39 |
+
lock.release()
|
| 40 |
+
await self._release_ref(session_key)
|
backend/core/tool_cache.py
ADDED
|
@@ -0,0 +1,102 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
"""
|
| 2 |
+
工具调用缓存 - 避免重复执行相同工具调用
|
| 3 |
+
预期收益: 相同工具调用 -97%, 减少API调用
|
| 4 |
+
|
| 5 |
+
关键特性:
|
| 6 |
+
- SHA256 哈希为缓存键
|
| 7 |
+
- TTL 过期机制
|
| 8 |
+
- 线程安全
|
| 9 |
+
"""
|
| 10 |
+
|
| 11 |
+
import hashlib
|
| 12 |
+
import json
|
| 13 |
+
import time
|
| 14 |
+
import logging
|
| 15 |
+
from typing import Dict, Any, Optional, Tuple
|
| 16 |
+
|
| 17 |
+
log = logging.getLogger("qwen2api.tool_cache")
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class ToolCallCache:
|
| 21 |
+
"""工具调用结果缓存"""
|
| 22 |
+
|
| 23 |
+
def __init__(self, ttl_seconds: int = 300):
|
| 24 |
+
self.ttl = ttl_seconds
|
| 25 |
+
self.cache: Dict[str, Tuple[Any, float]] = {}
|
| 26 |
+
self.stats = {
|
| 27 |
+
"hits": 0,
|
| 28 |
+
"misses": 0,
|
| 29 |
+
"sets": 0,
|
| 30 |
+
}
|
| 31 |
+
|
| 32 |
+
def _make_key(self, tool_name: str, tool_input: Dict[str, Any]) -> str:
|
| 33 |
+
"""生成工具调用缓存键"""
|
| 34 |
+
try:
|
| 35 |
+
serialized = json.dumps(tool_input, sort_keys=True, ensure_ascii=False)
|
| 36 |
+
except (TypeError, ValueError):
|
| 37 |
+
serialized = str(tool_input)
|
| 38 |
+
|
| 39 |
+
hash_val = hashlib.sha256(serialized.encode()).hexdigest()[:16]
|
| 40 |
+
return f"{tool_name}:{hash_val}"
|
| 41 |
+
|
| 42 |
+
def get(self, tool_name: str, tool_input: Dict[str, Any]) -> Optional[Any]:
|
| 43 |
+
"""获取缓存的工具结果"""
|
| 44 |
+
key = self._make_key(tool_name, tool_input)
|
| 45 |
+
|
| 46 |
+
if key not in self.cache:
|
| 47 |
+
self.stats["misses"] += 1
|
| 48 |
+
return None
|
| 49 |
+
|
| 50 |
+
result, cached_at = self.cache[key]
|
| 51 |
+
|
| 52 |
+
# 检查过期
|
| 53 |
+
if time.time() - cached_at > self.ttl:
|
| 54 |
+
del self.cache[key]
|
| 55 |
+
self.stats["misses"] += 1
|
| 56 |
+
return None
|
| 57 |
+
|
| 58 |
+
self.stats["hits"] += 1
|
| 59 |
+
log.info(f"[ToolCache-HIT] {tool_name}: {key}")
|
| 60 |
+
return result
|
| 61 |
+
|
| 62 |
+
def set(self, tool_name: str, tool_input: Dict[str, Any], result: Any):
|
| 63 |
+
"""缓存工具调用结果"""
|
| 64 |
+
key = self._make_key(tool_name, tool_input)
|
| 65 |
+
self.cache[key] = (result, time.time())
|
| 66 |
+
self.stats["sets"] += 1
|
| 67 |
+
log.debug(f"[ToolCache-SET] {tool_name}: {key}")
|
| 68 |
+
|
| 69 |
+
def clear(self):
|
| 70 |
+
"""清空缓存"""
|
| 71 |
+
self.cache.clear()
|
| 72 |
+
log.info("[ToolCache] 已清空缓存")
|
| 73 |
+
|
| 74 |
+
def cleanup_expired(self):
|
| 75 |
+
"""清理过期缓存"""
|
| 76 |
+
now = time.time()
|
| 77 |
+
expired = [k for k, (_, t) in self.cache.items() if now - t > self.ttl]
|
| 78 |
+
for k in expired:
|
| 79 |
+
del self.cache[k]
|
| 80 |
+
if expired:
|
| 81 |
+
log.debug(f"[ToolCache] 清理了 {len(expired)} 条过期缓存")
|
| 82 |
+
|
| 83 |
+
def status(self) -> Dict[str, Any]:
|
| 84 |
+
"""缓存统计"""
|
| 85 |
+
now = time.time()
|
| 86 |
+
active = sum(1 for _, (_, t) in self.cache.items() if now - t < self.ttl)
|
| 87 |
+
total_requests = self.stats["hits"] + self.stats["misses"]
|
| 88 |
+
hit_rate = self.stats["hits"] / total_requests if total_requests > 0 else 0
|
| 89 |
+
|
| 90 |
+
return {
|
| 91 |
+
"total_cached": len(self.cache),
|
| 92 |
+
"active": active,
|
| 93 |
+
"expired": len(self.cache) - active,
|
| 94 |
+
"hits": self.stats["hits"],
|
| 95 |
+
"misses": self.stats["misses"],
|
| 96 |
+
"hit_rate": f"{hit_rate*100:.1f}%",
|
| 97 |
+
"sets": self.stats["sets"],
|
| 98 |
+
}
|
| 99 |
+
|
| 100 |
+
|
| 101 |
+
# 全局工具缓存实例
|
| 102 |
+
tool_cache = ToolCallCache(ttl_seconds=300)
|
backend/core/upstream_file_cache.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import time
|
| 4 |
+
from dataclasses import dataclass
|
| 5 |
+
from typing import Any
|
| 6 |
+
|
| 7 |
+
from backend.core.database import AsyncJsonDB
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
@dataclass(slots=True)
|
| 11 |
+
class UpstreamFileCacheEntry:
|
| 12 |
+
session_key: str
|
| 13 |
+
account_email: str
|
| 14 |
+
sha256: str
|
| 15 |
+
ext: str
|
| 16 |
+
filename: str
|
| 17 |
+
remote_file_meta: dict[str, Any]
|
| 18 |
+
created_at: float
|
| 19 |
+
expires_at: float
|
| 20 |
+
|
| 21 |
+
def to_dict(self) -> dict[str, Any]:
|
| 22 |
+
return {
|
| 23 |
+
"session_key": self.session_key,
|
| 24 |
+
"account_email": self.account_email,
|
| 25 |
+
"sha256": self.sha256,
|
| 26 |
+
"ext": self.ext,
|
| 27 |
+
"filename": self.filename,
|
| 28 |
+
"remote_file_meta": self.remote_file_meta,
|
| 29 |
+
"created_at": self.created_at,
|
| 30 |
+
"expires_at": self.expires_at,
|
| 31 |
+
}
|
| 32 |
+
|
| 33 |
+
|
| 34 |
+
class UpstreamFileCache:
|
| 35 |
+
def __init__(self, db: AsyncJsonDB):
|
| 36 |
+
self.db = db
|
| 37 |
+
self.entries: list[UpstreamFileCacheEntry] = []
|
| 38 |
+
|
| 39 |
+
async def load(self):
|
| 40 |
+
data = await self.db.load()
|
| 41 |
+
self.entries = []
|
| 42 |
+
if isinstance(data, list):
|
| 43 |
+
for item in data:
|
| 44 |
+
if isinstance(item, dict):
|
| 45 |
+
self.entries.append(UpstreamFileCacheEntry(**item))
|
| 46 |
+
|
| 47 |
+
async def save(self):
|
| 48 |
+
await self.db.save([entry.to_dict() for entry in self.entries])
|
| 49 |
+
|
| 50 |
+
async def get(self, session_key: str, account_email: str, sha256: str, ext: str) -> UpstreamFileCacheEntry | None:
|
| 51 |
+
if not self.entries:
|
| 52 |
+
await self.load()
|
| 53 |
+
now = time.time()
|
| 54 |
+
for entry in self.entries:
|
| 55 |
+
if entry.expires_at and entry.expires_at < now:
|
| 56 |
+
continue
|
| 57 |
+
if entry.session_key == session_key and entry.account_email == account_email and entry.sha256 == sha256 and entry.ext == ext:
|
| 58 |
+
return entry
|
| 59 |
+
return None
|
| 60 |
+
|
| 61 |
+
async def set(self, entry: UpstreamFileCacheEntry):
|
| 62 |
+
self.entries = [e for e in self.entries if not (e.session_key == entry.session_key and e.account_email == entry.account_email and e.sha256 == entry.sha256 and e.ext == entry.ext)]
|
| 63 |
+
self.entries.append(entry)
|
| 64 |
+
await self.save()
|
| 65 |
+
|
| 66 |
+
async def cleanup_expired(self):
|
| 67 |
+
now = time.time()
|
| 68 |
+
before = len(self.entries)
|
| 69 |
+
self.entries = [entry for entry in self.entries if not entry.expires_at or entry.expires_at >= now]
|
| 70 |
+
if len(self.entries) != before:
|
| 71 |
+
await self.save()
|
backend/main.py
ADDED
|
@@ -0,0 +1,139 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import asyncio
|
| 2 |
+
import logging
|
| 3 |
+
from contextlib import asynccontextmanager
|
| 4 |
+
from fastapi import FastAPI
|
| 5 |
+
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
+
from fastapi.staticfiles import StaticFiles
|
| 7 |
+
import os
|
| 8 |
+
import sys
|
| 9 |
+
|
| 10 |
+
# 将项目根目录加入到 sys.path,解决直接运行 main.py 时找不到 backend 模块的问题
|
| 11 |
+
sys.path.append(os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
|
| 12 |
+
|
| 13 |
+
from backend.core.config import settings
|
| 14 |
+
from backend.core.database import AsyncJsonDB
|
| 15 |
+
from backend.core.account_pool import AccountPool
|
| 16 |
+
from backend.core.session_affinity import SessionAffinityStore
|
| 17 |
+
from backend.core.upstream_file_cache import UpstreamFileCache
|
| 18 |
+
from backend.core.session_lock import SessionLockRegistry
|
| 19 |
+
from backend.core.request_logging import configure_logging, request_context
|
| 20 |
+
from backend.services.qwen_client import QwenClient
|
| 21 |
+
from backend.services.file_store import LocalFileStore
|
| 22 |
+
from backend.services.context_offload import ContextOffloader
|
| 23 |
+
from backend.services.upstream_file_uploader import UpstreamFileUploader
|
| 24 |
+
import backend.api.models as models
|
| 25 |
+
from backend.api import admin, v1_chat, probes, anthropic, gemini, embeddings, images, videos, files_api
|
| 26 |
+
from backend.services.garbage_collector import garbage_collect_chats
|
| 27 |
+
from backend.services.context_cleanup import context_cleanup_loop
|
| 28 |
+
|
| 29 |
+
configure_logging(getattr(logging, settings.LOG_LEVEL.upper(), logging.INFO))
|
| 30 |
+
log = logging.getLogger("qwen2api")
|
| 31 |
+
|
| 32 |
+
@asynccontextmanager
|
| 33 |
+
async def lifespan(app: FastAPI):
|
| 34 |
+
with request_context(surface="startup"):
|
| 35 |
+
log.info("正在启动 qwen2API v2.0 企业网关...")
|
| 36 |
+
|
| 37 |
+
# 初始化数据存储 (带锁 JSON)
|
| 38 |
+
app.state.accounts_db = AsyncJsonDB(settings.ACCOUNTS_FILE, default_data=[])
|
| 39 |
+
app.state.users_db = AsyncJsonDB(settings.USERS_FILE, default_data=[])
|
| 40 |
+
app.state.captures_db = AsyncJsonDB(settings.CAPTURES_FILE, default_data=[])
|
| 41 |
+
app.state.session_affinity_db = AsyncJsonDB(settings.CONTEXT_AFFINITY_FILE, default_data=[])
|
| 42 |
+
app.state.context_cache_db = AsyncJsonDB(settings.CONTEXT_CACHE_FILE, default_data=[])
|
| 43 |
+
app.state.uploaded_files_db = AsyncJsonDB(settings.UPLOADED_FILES_FILE, default_data=[])
|
| 44 |
+
|
| 45 |
+
# 初始化组件
|
| 46 |
+
app.state.account_pool = AccountPool(app.state.accounts_db, max_inflight=settings.MAX_INFLIGHT_PER_ACCOUNT)
|
| 47 |
+
app.state.qwen_client = QwenClient(app.state.account_pool)
|
| 48 |
+
app.state.qwen_executor = app.state.qwen_client.executor
|
| 49 |
+
app.state.file_store = LocalFileStore(settings.CONTEXT_GENERATED_DIR, app.state.uploaded_files_db)
|
| 50 |
+
app.state.session_affinity = SessionAffinityStore(app.state.session_affinity_db)
|
| 51 |
+
app.state.upstream_file_cache = UpstreamFileCache(app.state.context_cache_db)
|
| 52 |
+
app.state.context_offloader = ContextOffloader(settings)
|
| 53 |
+
app.state.upstream_file_uploader = UpstreamFileUploader(app.state.qwen_client, settings)
|
| 54 |
+
app.state.session_locks = SessionLockRegistry()
|
| 55 |
+
|
| 56 |
+
# 加载账号并启动后台清理任务
|
| 57 |
+
await app.state.account_pool.load()
|
| 58 |
+
await app.state.file_store.load()
|
| 59 |
+
await app.state.session_affinity.load()
|
| 60 |
+
await app.state.upstream_file_cache.load()
|
| 61 |
+
asyncio.create_task(garbage_collect_chats(app))
|
| 62 |
+
asyncio.create_task(context_cleanup_loop(app))
|
| 63 |
+
|
| 64 |
+
# 启动 chat_id 预热池(省上游 /chats/new 握手 500ms~6s)
|
| 65 |
+
# 注:原默认 target_per_account=5 在 21 账号下,每 30s 触发 ~100 次
|
| 66 |
+
# /chats/new 请求,会被 Qwen 风控降级为空 SSE。这里降到 1 个 + 长 TTL。
|
| 67 |
+
from backend.services.chat_id_pool import ChatIdPool
|
| 68 |
+
app.state.chat_id_pool = ChatIdPool(app.state.qwen_client, target_per_account=1, ttl_seconds=1800, default_model="qwen3.6-plus")
|
| 69 |
+
app.state.qwen_executor.chat_id_pool = app.state.chat_id_pool # 让 executor 直接访问
|
| 70 |
+
await app.state.chat_id_pool.start()
|
| 71 |
+
|
| 72 |
+
yield
|
| 73 |
+
|
| 74 |
+
with request_context(surface="shutdown"):
|
| 75 |
+
log.info("正在关闭网关服务...")
|
| 76 |
+
# 关闭 chat_id 池
|
| 77 |
+
pool = getattr(app.state, "chat_id_pool", None)
|
| 78 |
+
if pool:
|
| 79 |
+
await pool.stop()
|
| 80 |
+
# 关闭 HTTP 连接池
|
| 81 |
+
await app.state.qwen_client._http_client.aclose()
|
| 82 |
+
log.info("HTTP 连接池已关闭")
|
| 83 |
+
# 持久化 Playwright cookie 并关闭浏览器
|
| 84 |
+
try:
|
| 85 |
+
await app.state.qwen_client._save_cookies()
|
| 86 |
+
log.info("Playwright cookie 已持久化")
|
| 87 |
+
except Exception as e:
|
| 88 |
+
log.warning(f"保存 Playwright cookie 失败: {e}")
|
| 89 |
+
try:
|
| 90 |
+
if app.state.qwen_client._pw_context:
|
| 91 |
+
await app.state.qwen_client._pw_context.close()
|
| 92 |
+
if app.state.qwen_client._pw_browser:
|
| 93 |
+
await app.state.qwen_client._pw_browser.close()
|
| 94 |
+
if app.state.qwen_client._pw_playwright:
|
| 95 |
+
await app.state.qwen_client._pw_playwright.stop()
|
| 96 |
+
log.info("Playwright 浏览器已关闭")
|
| 97 |
+
except Exception as e:
|
| 98 |
+
log.warning(f"关闭 Playwright 浏览器失败: {e}")
|
| 99 |
+
|
| 100 |
+
app = FastAPI(title="qwen2API Enterprise Gateway", version="2.0.0", lifespan=lifespan)
|
| 101 |
+
|
| 102 |
+
app.add_middleware(
|
| 103 |
+
CORSMiddleware,
|
| 104 |
+
allow_origins=["*"],
|
| 105 |
+
allow_credentials=True,
|
| 106 |
+
allow_methods=["*"],
|
| 107 |
+
allow_headers=["*"],
|
| 108 |
+
)
|
| 109 |
+
|
| 110 |
+
# 挂载路由
|
| 111 |
+
app.include_router(v1_chat.router, tags=["OpenAI Compatible"])
|
| 112 |
+
app.include_router(models.router, tags=["Models"])
|
| 113 |
+
app.include_router(anthropic.router, tags=["Claude Compatible"])
|
| 114 |
+
app.include_router(gemini.router, tags=["Gemini Compatible"])
|
| 115 |
+
app.include_router(embeddings.router, tags=["Embeddings"])
|
| 116 |
+
app.include_router(images.router, tags=["Images"])
|
| 117 |
+
app.include_router(videos.router, tags=["Videos"])
|
| 118 |
+
app.include_router(files_api.router, tags=["Files"])
|
| 119 |
+
app.include_router(probes.router, tags=["Probes"])
|
| 120 |
+
app.include_router(admin.router, prefix="/api/admin", tags=["Dashboard Admin"])
|
| 121 |
+
|
| 122 |
+
@app.get("/api", tags=["System"])
|
| 123 |
+
async def root():
|
| 124 |
+
return {
|
| 125 |
+
"status": "qwen2API Enterprise Gateway is running",
|
| 126 |
+
"docs": "/docs",
|
| 127 |
+
"version": "2.0.0"
|
| 128 |
+
}
|
| 129 |
+
|
| 130 |
+
# 托管前端构建产物
|
| 131 |
+
FRONTEND_DIST = os.path.join(os.path.dirname(os.path.dirname(__file__)), "frontend", "dist")
|
| 132 |
+
if os.path.exists(FRONTEND_DIST):
|
| 133 |
+
app.mount("/", StaticFiles(directory=FRONTEND_DIST, html=True), name="frontend")
|
| 134 |
+
else:
|
| 135 |
+
log.warning(f"未找到前端构建目录: {FRONTEND_DIST},WebUI 将不可用。")
|
| 136 |
+
|
| 137 |
+
if __name__ == "__main__":
|
| 138 |
+
import uvicorn
|
| 139 |
+
uvicorn.run("backend.main:app", host="0.0.0.0", port=settings.PORT, workers=1)
|
backend/requirements.txt
ADDED
|
@@ -0,0 +1,10 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
fastapi
|
| 2 |
+
uvicorn[standard]
|
| 3 |
+
httpx[http2]
|
| 4 |
+
pydantic-settings
|
| 5 |
+
python-dotenv
|
| 6 |
+
python-multipart
|
| 7 |
+
tiktoken
|
| 8 |
+
curl_cffi
|
| 9 |
+
camoufox
|
| 10 |
+
oss2
|
backend/runtime/__init__.py
ADDED
|
@@ -0,0 +1,5 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from . import stream_presenter
|
| 4 |
+
|
| 5 |
+
__all__ = ["stream_presenter"]
|
backend/runtime/attachment_types.py
ADDED
|
@@ -0,0 +1,19 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass, field
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
@dataclass(slots=True)
|
| 8 |
+
class NormalizedAttachment:
|
| 9 |
+
file_id: str
|
| 10 |
+
filename: str = ""
|
| 11 |
+
content_type: str = "application/octet-stream"
|
| 12 |
+
source: str = "upload"
|
| 13 |
+
local_path: str = ""
|
| 14 |
+
sha256: str = ""
|
| 15 |
+
purpose: str = "context"
|
| 16 |
+
remote_file_id: str = ""
|
| 17 |
+
remote_object_key: str = ""
|
| 18 |
+
remote_parse_status: str = ""
|
| 19 |
+
remote_ref: dict[str, Any] = field(default_factory=dict)
|
backend/runtime/execution.py
ADDED
|
@@ -0,0 +1,1048 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import asyncio
|
| 4 |
+
import json
|
| 5 |
+
import logging
|
| 6 |
+
import re
|
| 7 |
+
from dataclasses import dataclass, field
|
| 8 |
+
from typing import Any, Awaitable, Callable
|
| 9 |
+
|
| 10 |
+
from backend.adapter.standard_request import CLAUDE_CODE_OPENAI_PROFILE, StandardRequest
|
| 11 |
+
from backend.core.config import settings
|
| 12 |
+
from backend.core.request_logging import update_request_context
|
| 13 |
+
from backend.runtime.stream_metrics import StreamMetrics
|
| 14 |
+
from backend.services import tool_parser
|
| 15 |
+
from backend.toolcall.normalize import normalize_tool_name
|
| 16 |
+
from backend.toolcall.stream_state import StreamingToolCallState
|
| 17 |
+
|
| 18 |
+
|
| 19 |
+
# Qwen 偶尔生成的毒性"工具不存在"或"无法继续"幻觉。
|
| 20 |
+
# 在流式收到前 20 字时识别,触发早期拦截 + retry 而不是流给客户端。
|
| 21 |
+
_TOXIC_REFUSAL_RE = re.compile(
|
| 22 |
+
# 英文:工具不存在/不可用
|
| 23 |
+
r"Tool\s+\S+\s+(?:does\s+not\s+exists?|is\s+not\s+(?:available|registered))"
|
| 24 |
+
r"|I\s+cannot\s+execute\s+this\s+tool"
|
| 25 |
+
# 英文:任务放弃/拒绝继续
|
| 26 |
+
r"|I[''\u2019]?\s*m\s+sorry[,. ]"
|
| 27 |
+
r"|I\s+cannot\s+(?:help|assist|proceed|continue|support|perform)"
|
| 28 |
+
r"|I[''\u2019]?m\s+not\s+(?:able|designed)\s+to"
|
| 29 |
+
r"|unable\s+to\s+(?:proceed|continue|perform|complete)"
|
| 30 |
+
# 中文:工具/操作不存在或无法继续
|
| 31 |
+
r"|该工具.{0,8}?不存在|工具.{0,12}?不存在"
|
| 32 |
+
r"|我(?:无法|不能|不可以)(?:继续|进行|支持|完成|操作|执行)"
|
| 33 |
+
r"|无法(?:进行|支持|完成|执行).{0,10}?操作"
|
| 34 |
+
r"|抱歉.{0,20}?(?:无法|不能|不支持)",
|
| 35 |
+
re.IGNORECASE,
|
| 36 |
+
)
|
| 37 |
+
|
| 38 |
+
|
| 39 |
+
log = logging.getLogger("qwen2api.runtime")
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
@dataclass(slots=True)
|
| 43 |
+
class RuntimeAttemptState:
|
| 44 |
+
answer_text: str = ""
|
| 45 |
+
reasoning_text: str = ""
|
| 46 |
+
tool_calls: list[dict[str, Any]] = field(default_factory=list)
|
| 47 |
+
blocked_tool_names: list[str] = field(default_factory=list)
|
| 48 |
+
finish_reason: str = "stop"
|
| 49 |
+
raw_events: list[dict[str, Any]] = field(default_factory=list)
|
| 50 |
+
emitted_visible_output: bool = False
|
| 51 |
+
stage_metrics: dict[str, float] = field(default_factory=dict)
|
| 52 |
+
|
| 53 |
+
|
| 54 |
+
@dataclass(slots=True)
|
| 55 |
+
class RuntimeExecutionResult:
|
| 56 |
+
state: RuntimeAttemptState
|
| 57 |
+
chat_id: str | None
|
| 58 |
+
acc: Any | None
|
| 59 |
+
|
| 60 |
+
|
| 61 |
+
@dataclass(slots=True)
|
| 62 |
+
class RuntimeToolDirective:
|
| 63 |
+
tool_blocks: list[dict[str, Any]] = field(default_factory=list)
|
| 64 |
+
stop_reason: str = "end_turn"
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
@dataclass(slots=True)
|
| 68 |
+
class RuntimeRetryDirective:
|
| 69 |
+
retry: bool
|
| 70 |
+
next_prompt: str
|
| 71 |
+
reason: str | None = None
|
| 72 |
+
|
| 73 |
+
|
| 74 |
+
@dataclass(slots=True)
|
| 75 |
+
class RuntimeRetryContinuation:
|
| 76 |
+
should_continue: bool
|
| 77 |
+
next_prompt: str
|
| 78 |
+
|
| 79 |
+
|
| 80 |
+
@dataclass(slots=True)
|
| 81 |
+
class RuntimeRetryLoop:
|
| 82 |
+
prompt: str
|
| 83 |
+
max_attempts: int
|
| 84 |
+
|
| 85 |
+
|
| 86 |
+
@dataclass(slots=True)
|
| 87 |
+
class RuntimeAttemptPlan:
|
| 88 |
+
loop: RuntimeRetryLoop
|
| 89 |
+
prompt: str
|
| 90 |
+
|
| 91 |
+
|
| 92 |
+
@dataclass(slots=True)
|
| 93 |
+
class AnthropicStreamCompletionResult:
|
| 94 |
+
chunks: list[str]
|
| 95 |
+
|
| 96 |
+
|
| 97 |
+
@dataclass(slots=True)
|
| 98 |
+
class AnthropicStreamSuccessResult:
|
| 99 |
+
chunks: list[str]
|
| 100 |
+
usage_delta: int
|
| 101 |
+
|
| 102 |
+
|
| 103 |
+
@dataclass(slots=True)
|
| 104 |
+
class RuntimeAttemptOutcome:
|
| 105 |
+
execution: RuntimeExecutionResult
|
| 106 |
+
continuation: RuntimeRetryContinuation
|
| 107 |
+
|
| 108 |
+
|
| 109 |
+
@dataclass(slots=True)
|
| 110 |
+
class RuntimeAttemptCursor:
|
| 111 |
+
index: int
|
| 112 |
+
number: int
|
| 113 |
+
|
| 114 |
+
|
| 115 |
+
TRAILING_IDLE_AFTER_TOOL_SECONDS = 2.0
|
| 116 |
+
|
| 117 |
+
|
| 118 |
+
__all__ = [
|
| 119 |
+
"RuntimeAttemptState",
|
| 120 |
+
"RuntimeExecutionResult",
|
| 121 |
+
"RuntimeToolDirective",
|
| 122 |
+
"RuntimeRetryDirective",
|
| 123 |
+
"RuntimeRetryContinuation",
|
| 124 |
+
"RuntimeRetryLoop",
|
| 125 |
+
"RuntimeAttemptPlan",
|
| 126 |
+
"AnthropicStreamCompletionResult",
|
| 127 |
+
"AnthropicStreamSuccessResult",
|
| 128 |
+
"RuntimeAttemptOutcome",
|
| 129 |
+
"RuntimeAttemptCursor",
|
| 130 |
+
"anthropic_stream_stop_reason",
|
| 131 |
+
"anthropic_stream_usage_delta",
|
| 132 |
+
"build_retry_loop",
|
| 133 |
+
"build_tool_directive",
|
| 134 |
+
"build_usage_delta_factory",
|
| 135 |
+
"begin_runtime_attempt",
|
| 136 |
+
"cleanup_runtime_resources",
|
| 137 |
+
"collect_completion_run",
|
| 138 |
+
"collect_completion_run_with_recovery",
|
| 139 |
+
"continue_after_retry_directive",
|
| 140 |
+
"evaluate_retry_directive",
|
| 141 |
+
"extract_blocked_tool_names",
|
| 142 |
+
"finalize_anthropic_stream_success",
|
| 143 |
+
"complete_anthropic_stream_success",
|
| 144 |
+
"has_recent_search_no_results",
|
| 145 |
+
"has_recent_unchanged_read_result",
|
| 146 |
+
"inject_assistant_message",
|
| 147 |
+
"native_tool_calls_to_markup",
|
| 148 |
+
"parse_tool_directive_once",
|
| 149 |
+
"plan_runtime_attempts",
|
| 150 |
+
"recent_same_tool_identity_count",
|
| 151 |
+
"request_max_attempts",
|
| 152 |
+
"retryable_usage_delta",
|
| 153 |
+
"should_force_finish_after_tool_use",
|
| 154 |
+
"tool_identity",
|
| 155 |
+
]
|
| 156 |
+
|
| 157 |
+
|
| 158 |
+
def begin_runtime_attempt(attempt_index: int) -> RuntimeAttemptCursor:
|
| 159 |
+
cursor = RuntimeAttemptCursor(index=attempt_index, number=attempt_index + 1)
|
| 160 |
+
update_request_context(stream_attempt=cursor.number)
|
| 161 |
+
return cursor
|
| 162 |
+
|
| 163 |
+
|
| 164 |
+
def should_force_finish_after_tool_use(stop_reason: str, trailing_idle_seconds: float, visible_output_after_tool: bool) -> bool:
|
| 165 |
+
return stop_reason == "tool_use" and trailing_idle_seconds >= TRAILING_IDLE_AFTER_TOOL_SECONDS and not visible_output_after_tool
|
| 166 |
+
|
| 167 |
+
|
| 168 |
+
def extract_blocked_tool_names(text: str, allowed_tool_names: list[str] | None = None) -> list[str]:
|
| 169 |
+
if not text:
|
| 170 |
+
return []
|
| 171 |
+
if "does not exist" not in text.lower():
|
| 172 |
+
return []
|
| 173 |
+
blocked = re.findall(r"Tool\s+([A-Za-z0-9_.:-]+)\s+does not exists?\.?", text)
|
| 174 |
+
if not blocked:
|
| 175 |
+
return []
|
| 176 |
+
if not allowed_tool_names:
|
| 177 |
+
return blocked
|
| 178 |
+
return [normalize_tool_name(name, allowed_tool_names) for name in blocked]
|
| 179 |
+
|
| 180 |
+
|
| 181 |
+
def _recent_message_texts(messages: list[dict[str, Any]] | None, *, limit: int = 10) -> list[str]:
|
| 182 |
+
texts: list[str] = []
|
| 183 |
+
checked = 0
|
| 184 |
+
for msg in reversed(messages or []):
|
| 185 |
+
checked += 1
|
| 186 |
+
content = msg.get("content", "")
|
| 187 |
+
parts: list[str] = []
|
| 188 |
+
if isinstance(content, str):
|
| 189 |
+
parts.append(content)
|
| 190 |
+
elif isinstance(content, list):
|
| 191 |
+
for part in content:
|
| 192 |
+
if isinstance(part, dict):
|
| 193 |
+
if part.get("type") == "text":
|
| 194 |
+
parts.append(part.get("text", ""))
|
| 195 |
+
elif part.get("type") == "tool_result":
|
| 196 |
+
inner = part.get("content", "")
|
| 197 |
+
if isinstance(inner, str):
|
| 198 |
+
parts.append(inner)
|
| 199 |
+
elif isinstance(inner, list):
|
| 200 |
+
for inner_part in inner:
|
| 201 |
+
if isinstance(inner_part, dict) and inner_part.get("type") == "text":
|
| 202 |
+
parts.append(inner_part.get("text", ""))
|
| 203 |
+
elif isinstance(part, str):
|
| 204 |
+
parts.append(part)
|
| 205 |
+
merged = "\n".join(text for text in parts if text)
|
| 206 |
+
if merged:
|
| 207 |
+
texts.append(merged)
|
| 208 |
+
if checked >= limit:
|
| 209 |
+
break
|
| 210 |
+
return texts
|
| 211 |
+
|
| 212 |
+
|
| 213 |
+
def has_recent_unchanged_read_result(messages: list[dict[str, Any]] | None) -> bool:
|
| 214 |
+
return any("Unchanged since last read" in text for text in _recent_message_texts(messages))
|
| 215 |
+
|
| 216 |
+
|
| 217 |
+
def has_recent_search_no_results(messages: list[dict[str, Any]] | None) -> bool:
|
| 218 |
+
for text in _recent_message_texts(messages):
|
| 219 |
+
lowered = text.lower()
|
| 220 |
+
if "websearch" not in lowered:
|
| 221 |
+
continue
|
| 222 |
+
if "did 0 searches" in lowered or '"results": []' in lowered or '"matches": []' in lowered:
|
| 223 |
+
return True
|
| 224 |
+
return False
|
| 225 |
+
|
| 226 |
+
|
| 227 |
+
def tool_identity(tool_name: str, tool_input: Any = None) -> str:
|
| 228 |
+
try:
|
| 229 |
+
if tool_name == "Read" and isinstance(tool_input, dict):
|
| 230 |
+
return f"Read::{tool_input.get('file_path', '').strip()}"
|
| 231 |
+
if tool_name == "read" and isinstance(tool_input, dict):
|
| 232 |
+
return f"read::{tool_input.get('path', '').strip()}"
|
| 233 |
+
return f"{tool_name}::{json.dumps(tool_input or {}, ensure_ascii=False, sort_keys=True)}"
|
| 234 |
+
except Exception:
|
| 235 |
+
return tool_name or ""
|
| 236 |
+
|
| 237 |
+
|
| 238 |
+
def recent_same_tool_identity_count(messages: list[dict[str, Any]] | None, tool_name: str, tool_input: Any = None) -> int:
|
| 239 |
+
target = tool_identity(tool_name, tool_input)
|
| 240 |
+
count = 0
|
| 241 |
+
started = False
|
| 242 |
+
for msg in reversed(messages or []):
|
| 243 |
+
if msg.get("role") != "assistant":
|
| 244 |
+
continue
|
| 245 |
+
content = msg.get("content", [])
|
| 246 |
+
if not isinstance(content, list):
|
| 247 |
+
if started:
|
| 248 |
+
break
|
| 249 |
+
continue
|
| 250 |
+
tools = [b for b in content if isinstance(b, dict) and b.get("type") == "tool_use" and b.get("name")]
|
| 251 |
+
if not tools:
|
| 252 |
+
if started:
|
| 253 |
+
break
|
| 254 |
+
continue
|
| 255 |
+
started = True
|
| 256 |
+
if len(tools) == 1 and tool_identity(tools[0].get("name", ""), tools[0].get("input", {})) == target:
|
| 257 |
+
count += 1
|
| 258 |
+
continue
|
| 259 |
+
break
|
| 260 |
+
return count
|
| 261 |
+
|
| 262 |
+
|
| 263 |
+
def has_recent_openai_same_tool_call(history_messages: list[dict[str, Any]] | None, tool_name: str, tool_input: Any = None) -> bool:
|
| 264 |
+
target = tool_identity(tool_name, tool_input)
|
| 265 |
+
for msg in reversed(history_messages or []):
|
| 266 |
+
if msg.get("role") != "assistant":
|
| 267 |
+
continue
|
| 268 |
+
tool_calls = msg.get("tool_calls")
|
| 269 |
+
if not isinstance(tool_calls, list) or not tool_calls:
|
| 270 |
+
continue
|
| 271 |
+
if len(tool_calls) != 1:
|
| 272 |
+
return False
|
| 273 |
+
fn = tool_calls[0].get("function", {}) if isinstance(tool_calls[0], dict) else {}
|
| 274 |
+
name = fn.get("name", "")
|
| 275 |
+
raw_args = fn.get("arguments", "{}")
|
| 276 |
+
try:
|
| 277 |
+
parsed_args = json.loads(raw_args) if isinstance(raw_args, str) and raw_args else raw_args
|
| 278 |
+
except (json.JSONDecodeError, ValueError):
|
| 279 |
+
parsed_args = {"raw": raw_args}
|
| 280 |
+
return tool_identity(name, parsed_args) == target
|
| 281 |
+
return False
|
| 282 |
+
|
| 283 |
+
|
| 284 |
+
def has_invalid_textual_tool_contract(answer_text: str) -> bool:
|
| 285 |
+
if not answer_text:
|
| 286 |
+
return False
|
| 287 |
+
if "##TOOL_CALL##" not in answer_text and "<tool_call>" not in answer_text:
|
| 288 |
+
return False
|
| 289 |
+
compact = answer_text.strip()
|
| 290 |
+
tc_m = re.search(r'##TOOL_CALL##\s*(.*?)\s*##END_CALL##', compact, re.DOTALL | re.IGNORECASE)
|
| 291 |
+
if tc_m:
|
| 292 |
+
try:
|
| 293 |
+
obj = json.loads(tc_m.group(1))
|
| 294 |
+
except (json.JSONDecodeError, ValueError):
|
| 295 |
+
return True
|
| 296 |
+
tool_input = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {}))))
|
| 297 |
+
return isinstance(tool_input, str)
|
| 298 |
+
xml_m = re.search(r'<tool_call>\s*(.*?)\s*</tool_call>', compact, re.DOTALL | re.IGNORECASE)
|
| 299 |
+
if xml_m:
|
| 300 |
+
try:
|
| 301 |
+
obj = json.loads(xml_m.group(1))
|
| 302 |
+
except (json.JSONDecodeError, ValueError):
|
| 303 |
+
return True
|
| 304 |
+
tool_input = obj.get("input", obj.get("args", obj.get("arguments", obj.get("parameters", {}))))
|
| 305 |
+
return isinstance(tool_input, str)
|
| 306 |
+
return False
|
| 307 |
+
|
| 308 |
+
|
| 309 |
+
def should_retry_textual_tool_contract(answer_text: str) -> bool:
|
| 310 |
+
if not answer_text:
|
| 311 |
+
return False
|
| 312 |
+
if "##TOOL_CALL##" in answer_text or "<tool_call>" in answer_text:
|
| 313 |
+
return True
|
| 314 |
+
return False
|
| 315 |
+
|
| 316 |
+
|
| 317 |
+
def native_tool_calls_to_markup(tool_calls: list[dict[str, Any]]) -> str:
|
| 318 |
+
parts: list[str] = []
|
| 319 |
+
for tool_call in tool_calls:
|
| 320 |
+
parts.append(
|
| 321 |
+
f'<tool_call>{{"name": {json.dumps(tool_call["name"])}, "input": {json.dumps(tool_call.get("input", {}), ensure_ascii=False)}}}</tool_call>'
|
| 322 |
+
)
|
| 323 |
+
return "\n".join(parts)
|
| 324 |
+
|
| 325 |
+
|
| 326 |
+
async def run_runtime_attempt(
|
| 327 |
+
*,
|
| 328 |
+
client,
|
| 329 |
+
request: StandardRequest,
|
| 330 |
+
current_prompt: str,
|
| 331 |
+
history_messages: list[dict[str, Any]] | None,
|
| 332 |
+
attempt_index: int,
|
| 333 |
+
max_attempts: int,
|
| 334 |
+
allow_after_visible_output: bool = False,
|
| 335 |
+
capture_events: bool = True,
|
| 336 |
+
on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None,
|
| 337 |
+
) -> RuntimeAttemptOutcome:
|
| 338 |
+
attempt_cursor = begin_runtime_attempt(attempt_index)
|
| 339 |
+
execution = await collect_completion_run(
|
| 340 |
+
client,
|
| 341 |
+
request,
|
| 342 |
+
current_prompt,
|
| 343 |
+
capture_events=capture_events,
|
| 344 |
+
on_delta=on_delta,
|
| 345 |
+
)
|
| 346 |
+
retry = evaluate_retry_directive(
|
| 347 |
+
request=request,
|
| 348 |
+
current_prompt=current_prompt,
|
| 349 |
+
history_messages=history_messages,
|
| 350 |
+
attempt_index=attempt_cursor.index,
|
| 351 |
+
max_attempts=max_attempts,
|
| 352 |
+
state=execution.state,
|
| 353 |
+
allow_after_visible_output=allow_after_visible_output,
|
| 354 |
+
)
|
| 355 |
+
preserve_chat = bool(getattr(request, 'persistent_session', False))
|
| 356 |
+
continuation = await continue_after_retry_directive(
|
| 357 |
+
client=client,
|
| 358 |
+
execution=execution,
|
| 359 |
+
retry=retry,
|
| 360 |
+
preserve_chat=preserve_chat,
|
| 361 |
+
)
|
| 362 |
+
return RuntimeAttemptOutcome(execution=execution, continuation=continuation)
|
| 363 |
+
|
| 364 |
+
|
| 365 |
+
async def collect_completion_run(
|
| 366 |
+
client,
|
| 367 |
+
request: StandardRequest,
|
| 368 |
+
prompt: str,
|
| 369 |
+
*,
|
| 370 |
+
capture_events: bool = True,
|
| 371 |
+
on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None,
|
| 372 |
+
) -> RuntimeExecutionResult:
|
| 373 |
+
chat_id = None
|
| 374 |
+
acc = None
|
| 375 |
+
answer_fragments: list[str] = []
|
| 376 |
+
reasoning_fragments: list[str] = []
|
| 377 |
+
native_tool_calls: list[dict[str, Any]] = []
|
| 378 |
+
tool_state = StreamingToolCallState()
|
| 379 |
+
emitted_visible_output = False
|
| 380 |
+
first_event_marked = False
|
| 381 |
+
raw_events: list[dict[str, Any]] = []
|
| 382 |
+
metrics = StreamMetrics()
|
| 383 |
+
|
| 384 |
+
# 初始化 Tool Sieve 用于实时检测
|
| 385 |
+
tool_sieve = None
|
| 386 |
+
if request.tools:
|
| 387 |
+
tool_sieve = tool_parser.ToolSieve(request.tool_names)
|
| 388 |
+
log.info("[收集完成] 工具过滤器已启用,工具列表: %s", request.tool_names)
|
| 389 |
+
|
| 390 |
+
def _finalize_result(*, reason: str | None = None) -> RuntimeExecutionResult:
|
| 391 |
+
answer_text = "".join(answer_fragments)
|
| 392 |
+
reasoning_text = "".join(reasoning_fragments)
|
| 393 |
+
if native_tool_calls and not answer_text:
|
| 394 |
+
answer_text = native_tool_calls_to_markup(native_tool_calls)
|
| 395 |
+
|
| 396 |
+
# 关键修复:强制解析最终文本中的工具调用
|
| 397 |
+
detected_tool_calls = native_tool_calls
|
| 398 |
+
final_finish_reason = "tool_calls" if native_tool_calls else "stop"
|
| 399 |
+
|
| 400 |
+
# 第一重:刷新 Tool Sieve
|
| 401 |
+
if tool_sieve and not native_tool_calls:
|
| 402 |
+
flush_events = tool_sieve.flush()
|
| 403 |
+
for evt in flush_events:
|
| 404 |
+
if evt.get("type") == "tool_calls":
|
| 405 |
+
calls = evt.get("calls", [])
|
| 406 |
+
if calls:
|
| 407 |
+
# 转换为标准格式
|
| 408 |
+
import uuid
|
| 409 |
+
detected_tool_calls = [{
|
| 410 |
+
"type": "tool_use",
|
| 411 |
+
"id": f"toolu_{uuid.uuid4().hex[:8]}",
|
| 412 |
+
"name": call["name"],
|
| 413 |
+
"input": call["input"]
|
| 414 |
+
} for call in calls]
|
| 415 |
+
final_finish_reason = "tool_calls"
|
| 416 |
+
log.info(
|
| 417 |
+
"[Collect] ✓ Tool Sieve 刷新检测到工具调用: tools=%s",
|
| 418 |
+
[t.get("name") for t in detected_tool_calls],
|
| 419 |
+
)
|
| 420 |
+
break
|
| 421 |
+
elif evt.get("type") == "content":
|
| 422 |
+
# 剩余文本内容
|
| 423 |
+
pass
|
| 424 |
+
|
| 425 |
+
# 第二重:解析最终文本
|
| 426 |
+
if not detected_tool_calls and request.tools and answer_text:
|
| 427 |
+
# 尝试从最终文本中解析工具调用
|
| 428 |
+
tool_blocks, stop_reason = tool_parser.parse_tool_calls_silent(answer_text, request.tools)
|
| 429 |
+
tool_use_blocks = [b for b in tool_blocks if b.get("type") == "tool_use"]
|
| 430 |
+
|
| 431 |
+
if tool_use_blocks and stop_reason == "tool_use":
|
| 432 |
+
# 找到工具调用!
|
| 433 |
+
detected_tool_calls = tool_use_blocks
|
| 434 |
+
final_finish_reason = "tool_calls"
|
| 435 |
+
|
| 436 |
+
# 从文本中移除工具调用部分
|
| 437 |
+
text_blocks = [b for b in tool_blocks if b.get("type") == "text"]
|
| 438 |
+
if text_blocks:
|
| 439 |
+
answer_text = text_blocks[0].get("text", "")
|
| 440 |
+
else:
|
| 441 |
+
answer_text = ""
|
| 442 |
+
|
| 443 |
+
log.info(
|
| 444 |
+
"[Collect] ✓ 最终文本解析检测到工具调用: tools=%s, cleaned_text_len=%s",
|
| 445 |
+
[t.get("name") for t in detected_tool_calls],
|
| 446 |
+
len(answer_text),
|
| 447 |
+
)
|
| 448 |
+
|
| 449 |
+
# 检查空输出
|
| 450 |
+
if not detected_tool_calls and not answer_text.strip() and not reasoning_text.strip():
|
| 451 |
+
log.warning(
|
| 452 |
+
"[收集完成] 上游返回空输出: 原因=%s 会话=%s",
|
| 453 |
+
reason,
|
| 454 |
+
chat_id,
|
| 455 |
+
)
|
| 456 |
+
# 如果有 reasoning 但没有 visible output,说明模型只输出了思考过程
|
| 457 |
+
if reasoning_text.strip():
|
| 458 |
+
log.warning("[收集完成] 模型只返回了推理内容,没有可见输出")
|
| 459 |
+
# 空响应 flush 该账号池(同批次预热的可能都是坏的),下次走新建
|
| 460 |
+
try:
|
| 461 |
+
pool = getattr(client, "executor", None) and getattr(client.executor, "chat_id_pool", None)
|
| 462 |
+
if pool is not None and acc is not None:
|
| 463 |
+
import asyncio as _aio
|
| 464 |
+
_aio.create_task(pool.flush_account(acc.email))
|
| 465 |
+
except Exception:
|
| 466 |
+
pass
|
| 467 |
+
|
| 468 |
+
if reason:
|
| 469 |
+
log.info(
|
| 470 |
+
"[收集完成] 原因=%s 会话=%s 工具调用=%s 答复字数=%s 推理字数=%s 结束原因=%s",
|
| 471 |
+
reason,
|
| 472 |
+
chat_id,
|
| 473 |
+
len(detected_tool_calls),
|
| 474 |
+
len(answer_text),
|
| 475 |
+
len(reasoning_text),
|
| 476 |
+
final_finish_reason,
|
| 477 |
+
)
|
| 478 |
+
metrics.mark("stream_finish", float(len(raw_events)))
|
| 479 |
+
state = RuntimeAttemptState(
|
| 480 |
+
answer_text=answer_text,
|
| 481 |
+
reasoning_text=reasoning_text,
|
| 482 |
+
tool_calls=detected_tool_calls,
|
| 483 |
+
blocked_tool_names=extract_blocked_tool_names(answer_text.strip(), request.tool_names),
|
| 484 |
+
finish_reason=final_finish_reason,
|
| 485 |
+
raw_events=raw_events,
|
| 486 |
+
emitted_visible_output=emitted_visible_output,
|
| 487 |
+
stage_metrics=metrics.summary(),
|
| 488 |
+
)
|
| 489 |
+
return RuntimeExecutionResult(state=state, chat_id=chat_id, acc=acc)
|
| 490 |
+
|
| 491 |
+
async for item in client.chat_stream_events_with_retry(
|
| 492 |
+
request.resolved_model,
|
| 493 |
+
prompt,
|
| 494 |
+
has_custom_tools=bool(request.tools),
|
| 495 |
+
files=getattr(request, "upstream_files", None),
|
| 496 |
+
fixed_account=getattr(request, "bound_account", None),
|
| 497 |
+
existing_chat_id=getattr(request, "upstream_chat_id", None),
|
| 498 |
+
):
|
| 499 |
+
if item.get("type") == "meta":
|
| 500 |
+
chat_id = item.get("chat_id")
|
| 501 |
+
acc = item.get("acc")
|
| 502 |
+
update_request_context(chat_id=chat_id)
|
| 503 |
+
metrics.mark("chat_created", float(len(raw_events)))
|
| 504 |
+
continue
|
| 505 |
+
if item.get("type") != "event":
|
| 506 |
+
continue
|
| 507 |
+
|
| 508 |
+
evt = item.get("event", {})
|
| 509 |
+
if capture_events:
|
| 510 |
+
raw_events.append(evt)
|
| 511 |
+
if evt.get("type") != "delta":
|
| 512 |
+
continue
|
| 513 |
+
|
| 514 |
+
phase = evt.get("phase", "")
|
| 515 |
+
content = evt.get("content", "")
|
| 516 |
+
|
| 517 |
+
if phase in ("think", "thinking_summary") and content:
|
| 518 |
+
reasoning_fragments.append(content)
|
| 519 |
+
emitted_visible_output = True
|
| 520 |
+
if not first_event_marked:
|
| 521 |
+
metrics.mark("first_event", float(len(raw_events)))
|
| 522 |
+
first_event_marked = True
|
| 523 |
+
if on_delta is not None:
|
| 524 |
+
await on_delta(evt, content, None)
|
| 525 |
+
continue
|
| 526 |
+
|
| 527 |
+
if phase == "answer" and content:
|
| 528 |
+
answer_fragments.append(content)
|
| 529 |
+
|
| 530 |
+
# 毒性拒绝���期拦截:Qwen 偶尔幻觉出 "Tool X does not exists." 之类文本。
|
| 531 |
+
# 在标记 emitted_visible_output 之前识别并提前 finalize,让 evaluate_retry_directive
|
| 532 |
+
# 的 blocked_tool_name 分支能正常触发重试(否则 emitted=True 后就不 retry 了)。
|
| 533 |
+
if (
|
| 534 |
+
request.tools
|
| 535 |
+
and not emitted_visible_output
|
| 536 |
+
and len("".join(answer_fragments)) >= 20
|
| 537 |
+
):
|
| 538 |
+
early_answer = "".join(answer_fragments).strip()
|
| 539 |
+
if _TOXIC_REFUSAL_RE.search(early_answer):
|
| 540 |
+
toxic_blocked = extract_blocked_tool_names(early_answer, request.tool_names)
|
| 541 |
+
blocked_name = toxic_blocked[0] if toxic_blocked else "unknown"
|
| 542 |
+
log.warning(
|
| 543 |
+
"[收集完成] 污染拦截 %r (未流出客户端,触发重试)",
|
| 544 |
+
early_answer[:80],
|
| 545 |
+
)
|
| 546 |
+
return _finalize_result(reason=f"blocked_tool_name:{blocked_name}")
|
| 547 |
+
|
| 548 |
+
emitted_visible_output = True
|
| 549 |
+
if not first_event_marked:
|
| 550 |
+
metrics.mark("first_event", float(len(raw_events)))
|
| 551 |
+
first_event_marked = True
|
| 552 |
+
|
| 553 |
+
# Tool Sieve 实时检测
|
| 554 |
+
if tool_sieve:
|
| 555 |
+
sieve_events = tool_sieve.process_chunk(content)
|
| 556 |
+
for sieve_evt in sieve_events:
|
| 557 |
+
if sieve_evt.get("type") == "tool_calls":
|
| 558 |
+
# 检测到工具调用!
|
| 559 |
+
calls = sieve_evt.get("calls", [])
|
| 560 |
+
if calls:
|
| 561 |
+
import uuid
|
| 562 |
+
detected_calls = [{
|
| 563 |
+
"type": "tool_use",
|
| 564 |
+
"id": f"toolu_{uuid.uuid4().hex[:8]}",
|
| 565 |
+
"name": call["name"],
|
| 566 |
+
"input": call["input"]
|
| 567 |
+
} for call in calls]
|
| 568 |
+
native_tool_calls.extend(detected_calls)
|
| 569 |
+
log.info(
|
| 570 |
+
"[Collect] ✓ Tool Sieve 实时检测到工具调用: tools=%s",
|
| 571 |
+
[c.get("name") for c in detected_calls],
|
| 572 |
+
)
|
| 573 |
+
return _finalize_result(reason="tool_sieve_detected")
|
| 574 |
+
|
| 575 |
+
if on_delta is not None:
|
| 576 |
+
await on_delta(evt, content, None)
|
| 577 |
+
if request.tools:
|
| 578 |
+
answer_text = "".join(answer_fragments)
|
| 579 |
+
if len(answer_fragments) % 3 == 0 or "does not exist" in content.lower():
|
| 580 |
+
blocked_tool_names = extract_blocked_tool_names(answer_text.strip(), request.tool_names)
|
| 581 |
+
if blocked_tool_names:
|
| 582 |
+
return _finalize_result(reason=f"blocked_tool_name:{blocked_tool_names[0]}")
|
| 583 |
+
if "##TOOL_CALL##" in answer_text or "<tool_call>" in answer_text:
|
| 584 |
+
directive = parse_tool_directive_once(
|
| 585 |
+
request,
|
| 586 |
+
RuntimeAttemptState(answer_text=answer_text, reasoning_text="".join(reasoning_fragments)),
|
| 587 |
+
)
|
| 588 |
+
if directive.stop_reason == "tool_use":
|
| 589 |
+
return _finalize_result(reason="textual_tool_use")
|
| 590 |
+
continue
|
| 591 |
+
|
| 592 |
+
if phase == "tool_call":
|
| 593 |
+
emitted_visible_output = True
|
| 594 |
+
if not first_event_marked:
|
| 595 |
+
metrics.mark("first_event", float(len(raw_events)))
|
| 596 |
+
first_event_marked = True
|
| 597 |
+
completed_calls = tool_state.process_event(evt)
|
| 598 |
+
if completed_calls:
|
| 599 |
+
native_tool_calls.extend(completed_calls)
|
| 600 |
+
if on_delta is not None:
|
| 601 |
+
await on_delta(evt, None, completed_calls)
|
| 602 |
+
return _finalize_result(reason="native_tool_use")
|
| 603 |
+
|
| 604 |
+
return _finalize_result(reason="stream_end")
|
| 605 |
+
|
| 606 |
+
|
| 607 |
+
def parse_tool_directive_once(request: StandardRequest, state: RuntimeAttemptState) -> RuntimeToolDirective:
|
| 608 |
+
if state.tool_calls:
|
| 609 |
+
return RuntimeToolDirective(
|
| 610 |
+
tool_blocks=[
|
| 611 |
+
{
|
| 612 |
+
"type": "tool_use",
|
| 613 |
+
"id": tool_call["id"],
|
| 614 |
+
"name": normalize_tool_name(tool_call["name"], request.tool_names),
|
| 615 |
+
"input": tool_call.get("input", {}),
|
| 616 |
+
}
|
| 617 |
+
for tool_call in state.tool_calls
|
| 618 |
+
],
|
| 619 |
+
stop_reason="tool_use",
|
| 620 |
+
)
|
| 621 |
+
|
| 622 |
+
if request.tools and state.answer_text:
|
| 623 |
+
tool_blocks, stop_reason = tool_parser.parse_tool_calls_silent(state.answer_text, request.tools)
|
| 624 |
+
return RuntimeToolDirective(tool_blocks=tool_blocks, stop_reason=stop_reason)
|
| 625 |
+
|
| 626 |
+
return RuntimeToolDirective(tool_blocks=[{"type": "text", "text": state.answer_text}], stop_reason="end_turn")
|
| 627 |
+
|
| 628 |
+
|
| 629 |
+
# ==================== 截断续写 + 流式 warmup(P2-6 & P2-10 接入)====================
|
| 630 |
+
|
| 631 |
+
async def collect_completion_run_with_recovery(
|
| 632 |
+
client,
|
| 633 |
+
request: StandardRequest,
|
| 634 |
+
prompt: str,
|
| 635 |
+
*,
|
| 636 |
+
capture_events: bool = True,
|
| 637 |
+
on_delta: Callable[[dict[str, Any], str | None, list[dict[str, Any]] | None], Awaitable[None]] | None = None,
|
| 638 |
+
max_continuation: int = 2,
|
| 639 |
+
warmup_chars: int = 0,
|
| 640 |
+
guard_chars: int = 0,
|
| 641 |
+
) -> RuntimeExecutionResult:
|
| 642 |
+
"""collect_completion_run 的增强版,叠加两个能力:
|
| 643 |
+
|
| 644 |
+
1. **截断自动续写**(P2-6):初始流结束若 answer_text 含未闭合的 ##TOOL_CALL## 块,
|
| 645 |
+
最多追加 max_continuation 次续写请求,每次丢弃工具定义省上下文预算,
|
| 646 |
+
用 deduplicate_continuation 去除头尾重叠后拼接。
|
| 647 |
+
|
| 648 |
+
2. **流式 warmup/guard**(P2-10):当 warmup_chars>0 时,用 IncrementalTextStreamer
|
| 649 |
+
包装 on_delta 的 text 路径——起步累积 warmup_chars 字符后才放行,
|
| 650 |
+
任何时刻保留末尾 guard_chars 字符暂不发出,给跨 chunk 清洗预留空间。
|
| 651 |
+
|
| 652 |
+
保留向后兼容:不传可选参数 → 行为与 collect_completion_run 完全一致。
|
| 653 |
+
"""
|
| 654 |
+
from backend.services.truncation_recovery import (
|
| 655 |
+
build_continuation_prompt,
|
| 656 |
+
deduplicate_continuation,
|
| 657 |
+
is_truncated,
|
| 658 |
+
)
|
| 659 |
+
from backend.services.incremental_text_streamer import IncrementalTextStreamer
|
| 660 |
+
|
| 661 |
+
wrapped_on_delta = on_delta
|
| 662 |
+
streamer: IncrementalTextStreamer | None = None
|
| 663 |
+
if warmup_chars > 0 and on_delta is not None:
|
| 664 |
+
streamer = IncrementalTextStreamer(
|
| 665 |
+
warmup_chars=warmup_chars,
|
| 666 |
+
guard_chars=max(guard_chars, 64),
|
| 667 |
+
)
|
| 668 |
+
|
| 669 |
+
async def _wrapped(evt, text_chunk, tool_calls):
|
| 670 |
+
# 仅对纯文本 delta 做 warmup;tool_calls / thinking / native 直接透传
|
| 671 |
+
if text_chunk is None or tool_calls is not None or evt.get("phase") not in ("answer", "text"):
|
| 672 |
+
await on_delta(evt, text_chunk, tool_calls)
|
| 673 |
+
return
|
| 674 |
+
released = streamer.push(text_chunk)
|
| 675 |
+
if released:
|
| 676 |
+
await on_delta(evt, released, None)
|
| 677 |
+
|
| 678 |
+
wrapped_on_delta = _wrapped
|
| 679 |
+
|
| 680 |
+
result = await collect_completion_run(
|
| 681 |
+
client, request, prompt,
|
| 682 |
+
capture_events=capture_events,
|
| 683 |
+
on_delta=wrapped_on_delta,
|
| 684 |
+
)
|
| 685 |
+
|
| 686 |
+
# 若 warmup 还保留着尾部,flush 出去
|
| 687 |
+
if streamer is not None and on_delta is not None:
|
| 688 |
+
tail = streamer.finish()
|
| 689 |
+
if tail:
|
| 690 |
+
await on_delta({"phase": "answer"}, tail, None)
|
| 691 |
+
|
| 692 |
+
# 截断续写
|
| 693 |
+
continues = 0
|
| 694 |
+
while continues < max_continuation:
|
| 695 |
+
state = result.state
|
| 696 |
+
# 有已检出的工具调用就不续写(让客户端去执行那个 tool)
|
| 697 |
+
if state.tool_calls:
|
| 698 |
+
break
|
| 699 |
+
# 没 tools 的场景不做续写(纯聊天,截断检测无 ##TOOL_CALL## 参考点会误触发)
|
| 700 |
+
if not request.tools:
|
| 701 |
+
break
|
| 702 |
+
if not is_truncated(state.answer_text):
|
| 703 |
+
break
|
| 704 |
+
|
| 705 |
+
continues += 1
|
| 706 |
+
log.info(
|
| 707 |
+
"[TruncRecover] detected unclosed tool call, continuation attempt=%d chat_id=%s len=%d",
|
| 708 |
+
continues, result.chat_id, len(state.answer_text),
|
| 709 |
+
)
|
| 710 |
+
|
| 711 |
+
assistant_ctx, followup = build_continuation_prompt(state.answer_text, anchor_chars=2000)
|
| 712 |
+
# 续写 prompt = 原 prompt + assistant 已输出的锚点 + user 续写指令
|
| 713 |
+
cont_prompt = (
|
| 714 |
+
f"{prompt.rstrip()}\n\nAssistant: {assistant_ctx}\n\nHuman: {followup}\n\nAssistant:"
|
| 715 |
+
)
|
| 716 |
+
|
| 717 |
+
cont_result = await collect_completion_run(
|
| 718 |
+
client, request, cont_prompt,
|
| 719 |
+
capture_events=False,
|
| 720 |
+
on_delta=on_delta, # 不经过 streamer,续写内容直接透传
|
| 721 |
+
)
|
| 722 |
+
cont_text = cont_result.state.answer_text
|
| 723 |
+
if not cont_text or not cont_text.strip():
|
| 724 |
+
log.info("[TruncRecover] empty continuation, stopping")
|
| 725 |
+
break
|
| 726 |
+
|
| 727 |
+
deduped = deduplicate_continuation(state.answer_text, cont_text)
|
| 728 |
+
if not deduped.strip():
|
| 729 |
+
log.info("[TruncRecover] continuation fully overlapped existing, stopping")
|
| 730 |
+
break
|
| 731 |
+
|
| 732 |
+
merged_answer = state.answer_text + deduped
|
| 733 |
+
merged_state = RuntimeAttemptState(
|
| 734 |
+
answer_text=merged_answer,
|
| 735 |
+
reasoning_text=state.reasoning_text,
|
| 736 |
+
tool_calls=cont_result.state.tool_calls or state.tool_calls,
|
| 737 |
+
blocked_tool_names=cont_result.state.blocked_tool_names or state.blocked_tool_names,
|
| 738 |
+
finish_reason=cont_result.state.finish_reason or state.finish_reason,
|
| 739 |
+
raw_events=state.raw_events,
|
| 740 |
+
emitted_visible_output=state.emitted_visible_output or cont_result.state.emitted_visible_output,
|
| 741 |
+
stage_metrics=state.stage_metrics,
|
| 742 |
+
)
|
| 743 |
+
result = RuntimeExecutionResult(state=merged_state, chat_id=result.chat_id, acc=result.acc)
|
| 744 |
+
log.info(
|
| 745 |
+
"[TruncRecover] continuation=%d produced %d new chars; total=%d",
|
| 746 |
+
continues, len(deduped), len(merged_answer),
|
| 747 |
+
)
|
| 748 |
+
# 若续写完成后已闭合则收工
|
| 749 |
+
if not is_truncated(merged_answer):
|
| 750 |
+
break
|
| 751 |
+
|
| 752 |
+
return result
|
| 753 |
+
|
| 754 |
+
|
| 755 |
+
def build_tool_directive(
|
| 756 |
+
request: StandardRequest,
|
| 757 |
+
state: RuntimeAttemptState,
|
| 758 |
+
) -> RuntimeToolDirective:
|
| 759 |
+
directive = parse_tool_directive_once(request, state)
|
| 760 |
+
log.info(
|
| 761 |
+
f"[ToolDirective] tool_blocks={len(directive.tool_blocks)} stop_reason={directive.stop_reason} "
|
| 762 |
+
f"has_tool_use={any(b.get('type') == 'tool_use' for b in directive.tool_blocks)}"
|
| 763 |
+
)
|
| 764 |
+
return directive
|
| 765 |
+
|
| 766 |
+
|
| 767 |
+
def anthropic_stream_usage_delta(prompt: str, answer_text: str) -> int:
|
| 768 |
+
return len(answer_text) + len(prompt)
|
| 769 |
+
|
| 770 |
+
|
| 771 |
+
def anthropic_stream_stop_reason(request: StandardRequest, state: RuntimeAttemptState, pending_chunks: list[str]) -> str:
|
| 772 |
+
if state.tool_calls or any('"type": "tool_use"' in chunk for chunk in pending_chunks):
|
| 773 |
+
return "tool_use"
|
| 774 |
+
return build_tool_directive(request, state).stop_reason
|
| 775 |
+
|
| 776 |
+
|
| 777 |
+
def finalize_anthropic_stream_success(*, request: StandardRequest, prompt: str, execution: RuntimeExecutionResult, translator) -> AnthropicStreamSuccessResult:
|
| 778 |
+
stop_reason = anthropic_stream_stop_reason(request, execution.state, translator.pending_chunks)
|
| 779 |
+
chunks = translator.finalize(answer_text=execution.state.answer_text, stop_reason=stop_reason)
|
| 780 |
+
return AnthropicStreamSuccessResult(
|
| 781 |
+
chunks=chunks,
|
| 782 |
+
usage_delta=anthropic_stream_usage_delta(prompt, execution.state.answer_text),
|
| 783 |
+
)
|
| 784 |
+
|
| 785 |
+
|
| 786 |
+
async def complete_anthropic_stream_success(*, users_db, token: str, client, prompt: str, request: StandardRequest, execution: RuntimeExecutionResult, translator) -> AnthropicStreamCompletionResult:
|
| 787 |
+
from backend.services.auth_quota import add_used_tokens
|
| 788 |
+
|
| 789 |
+
stream_success = finalize_anthropic_stream_success(
|
| 790 |
+
request=request,
|
| 791 |
+
prompt=prompt,
|
| 792 |
+
execution=execution,
|
| 793 |
+
translator=translator,
|
| 794 |
+
)
|
| 795 |
+
await add_used_tokens(users_db, token, stream_success.usage_delta)
|
| 796 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id)
|
| 797 |
+
return AnthropicStreamCompletionResult(chunks=stream_success.chunks)
|
| 798 |
+
|
| 799 |
+
|
| 800 |
+
def inject_assistant_message(prompt: str, message: str) -> str:
|
| 801 |
+
next_prompt = prompt.rstrip()
|
| 802 |
+
if next_prompt.endswith("Assistant:"):
|
| 803 |
+
return next_prompt[:-len("Assistant:")] + message + "\nAssistant:"
|
| 804 |
+
return next_prompt + "\n\n" + message + "\nAssistant:"
|
| 805 |
+
|
| 806 |
+
|
| 807 |
+
def retryable_usage_delta(prompt: str):
|
| 808 |
+
return lambda execution, current_prompt=None: len(execution.state.answer_text) + len(current_prompt or prompt)
|
| 809 |
+
|
| 810 |
+
|
| 811 |
+
def build_usage_delta_factory(prompt: str) -> Callable[[RuntimeExecutionResult, Any | None], int]:
|
| 812 |
+
return lambda execution, current_prompt=None: len(execution.state.answer_text) + len(current_prompt or prompt)
|
| 813 |
+
|
| 814 |
+
|
| 815 |
+
def request_max_attempts(request: StandardRequest) -> int:
|
| 816 |
+
# 工具模式下给模型更多重试机会(毒性幻觉/重复调用场景常见),
|
| 817 |
+
# 原值 2 在多轮 retry 里太容易用完,升到 4
|
| 818 |
+
return 4 if request.tools else settings.MAX_RETRIES
|
| 819 |
+
|
| 820 |
+
|
| 821 |
+
def plan_runtime_attempts(request: StandardRequest, *, initial_prompt: str) -> RuntimeAttemptPlan:
|
| 822 |
+
loop = build_retry_loop(request, initial_prompt=initial_prompt)
|
| 823 |
+
return RuntimeAttemptPlan(loop=loop, prompt=loop.prompt)
|
| 824 |
+
|
| 825 |
+
|
| 826 |
+
def build_retry_loop(request: StandardRequest, *, initial_prompt: str) -> RuntimeRetryLoop:
|
| 827 |
+
return RuntimeRetryLoop(
|
| 828 |
+
prompt=initial_prompt,
|
| 829 |
+
max_attempts=request_max_attempts(request),
|
| 830 |
+
)
|
| 831 |
+
|
| 832 |
+
|
| 833 |
+
def evaluate_retry_directive(
|
| 834 |
+
*,
|
| 835 |
+
request: StandardRequest,
|
| 836 |
+
current_prompt: str,
|
| 837 |
+
history_messages: list[dict[str, Any]] | None,
|
| 838 |
+
attempt_index: int,
|
| 839 |
+
max_attempts: int,
|
| 840 |
+
state: RuntimeAttemptState,
|
| 841 |
+
allow_after_visible_output: bool = False,
|
| 842 |
+
) -> RuntimeRetryDirective:
|
| 843 |
+
if attempt_index >= max_attempts - 1:
|
| 844 |
+
return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None)
|
| 845 |
+
|
| 846 |
+
can_retry_after_output = allow_after_visible_output or not state.emitted_visible_output
|
| 847 |
+
|
| 848 |
+
def _retry(reason: str, next_prompt: str) -> RuntimeRetryDirective:
|
| 849 |
+
log.info(
|
| 850 |
+
"[重试] 原因=%s 第%s/%s次 客户端=%s 屏蔽=%s 结束原因=%s 已流出=%s",
|
| 851 |
+
reason,
|
| 852 |
+
attempt_index + 1,
|
| 853 |
+
max_attempts,
|
| 854 |
+
getattr(request, "client_profile", "-"),
|
| 855 |
+
state.blocked_tool_names[:3],
|
| 856 |
+
state.finish_reason,
|
| 857 |
+
state.emitted_visible_output,
|
| 858 |
+
)
|
| 859 |
+
return RuntimeRetryDirective(retry=True, next_prompt=next_prompt, reason=reason)
|
| 860 |
+
|
| 861 |
+
if state.blocked_tool_names and request.tools:
|
| 862 |
+
if not can_retry_after_output:
|
| 863 |
+
return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None)
|
| 864 |
+
blocked_name = normalize_tool_name(state.blocked_tool_names[0], request.tool_names)
|
| 865 |
+
return _retry(
|
| 866 |
+
f"blocked_tool_name:{blocked_name}",
|
| 867 |
+
tool_parser.inject_format_reminder(
|
| 868 |
+
current_prompt,
|
| 869 |
+
blocked_name,
|
| 870 |
+
client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE),
|
| 871 |
+
),
|
| 872 |
+
)
|
| 873 |
+
|
| 874 |
+
if request.tools:
|
| 875 |
+
directive: RuntimeToolDirective | None = None
|
| 876 |
+
if state.answer_text:
|
| 877 |
+
saw_contract_markup = should_retry_textual_tool_contract(state.answer_text)
|
| 878 |
+
if saw_contract_markup and can_retry_after_output:
|
| 879 |
+
if has_invalid_textual_tool_contract(state.answer_text):
|
| 880 |
+
fallback_tool_name = request.tool_names[0] if request.tool_names else "tool"
|
| 881 |
+
return _retry(
|
| 882 |
+
f"invalid_textual_tool_contract:{fallback_tool_name}",
|
| 883 |
+
tool_parser.inject_format_reminder(
|
| 884 |
+
current_prompt,
|
| 885 |
+
fallback_tool_name,
|
| 886 |
+
client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE),
|
| 887 |
+
),
|
| 888 |
+
)
|
| 889 |
+
directive = parse_tool_directive_once(request, state)
|
| 890 |
+
if directive.stop_reason != "tool_use":
|
| 891 |
+
fallback_tool_name = request.tool_names[0] if request.tool_names else "tool"
|
| 892 |
+
return _retry(
|
| 893 |
+
f"unparsed_textual_tool_contract:{fallback_tool_name}",
|
| 894 |
+
tool_parser.inject_format_reminder(
|
| 895 |
+
current_prompt,
|
| 896 |
+
fallback_tool_name,
|
| 897 |
+
client_profile=getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE),
|
| 898 |
+
),
|
| 899 |
+
)
|
| 900 |
+
if directive is None:
|
| 901 |
+
directive = parse_tool_directive_once(request, state)
|
| 902 |
+
if directive.stop_reason == "tool_use":
|
| 903 |
+
first_tool = next((b for b in directive.tool_blocks if b.get("type") == "tool_use"), None)
|
| 904 |
+
if first_tool:
|
| 905 |
+
repeated_same_tool = False
|
| 906 |
+
if getattr(request, "client_profile", CLAUDE_CODE_OPENAI_PROFILE) == "openclaw_openai":
|
| 907 |
+
repeated_same_tool = has_recent_openai_same_tool_call(
|
| 908 |
+
history_messages,
|
| 909 |
+
first_tool.get("name", ""),
|
| 910 |
+
first_tool.get("input", {}),
|
| 911 |
+
)
|
| 912 |
+
else:
|
| 913 |
+
repeated_same_tool = recent_same_tool_identity_count(
|
| 914 |
+
history_messages,
|
| 915 |
+
first_tool.get("name", ""),
|
| 916 |
+
first_tool.get("input", {}),
|
| 917 |
+
) >= 1
|
| 918 |
+
if repeated_same_tool and can_retry_after_output:
|
| 919 |
+
force_text = (
|
| 920 |
+
f"[强制要求]: 你已经用相同参数调用了 {first_tool.get('name')}。"
|
| 921 |
+
"不要重复相同的工具调用。"
|
| 922 |
+
"使用已有的工具结果,选择下一个相关工具或完成任务。"
|
| 923 |
+
"如果是配置文件任务,读取一次后直接编辑/写入文件,不要重复读取。"
|
| 924 |
+
f"\n[MANDATORY]: You already called {first_tool.get('name')} with the same input. "
|
| 925 |
+
"Do NOT repeat the same tool call. "
|
| 926 |
+
"Use the tool result you already have and either choose the next relevant tool or finish the task. "
|
| 927 |
+
"If this is a config-file task, read once and then edit/write the file instead of rereading it."
|
| 928 |
+
)
|
| 929 |
+
return _retry(
|
| 930 |
+
f"repeated_same_tool:{first_tool.get('name', '')}",
|
| 931 |
+
inject_assistant_message(current_prompt, force_text),
|
| 932 |
+
)
|
| 933 |
+
if (
|
| 934 |
+
first_tool
|
| 935 |
+
and first_tool.get("name") == "Read"
|
| 936 |
+
and has_recent_unchanged_read_result(history_messages)
|
| 937 |
+
):
|
| 938 |
+
if can_retry_after_output:
|
| 939 |
+
force_text = (
|
| 940 |
+
"[强制要求]: 你刚收到'Unchanged since last read'(文件未改变)。"
|
| 941 |
+
"不要再次读取同一个文件。"
|
| 942 |
+
"现在选择其他工具或完成任务。"
|
| 943 |
+
"\n[MANDATORY]: You just received 'Unchanged since last read'. "
|
| 944 |
+
"Do NOT call Read again. Choose another tool or finish the task."
|
| 945 |
+
)
|
| 946 |
+
return _retry(
|
| 947 |
+
"unchanged_read_result",
|
| 948 |
+
inject_assistant_message(current_prompt, force_text),
|
| 949 |
+
)
|
| 950 |
+
else:
|
| 951 |
+
log.warning(f"[Runtime] Blocked repeated Read after 'Unchanged since last read', but cannot retry")
|
| 952 |
+
|
| 953 |
+
# 防止自动调用Agent工具
|
| 954 |
+
if (
|
| 955 |
+
first_tool
|
| 956 |
+
and first_tool.get("name") == "Agent"
|
| 957 |
+
and can_retry_after_output
|
| 958 |
+
):
|
| 959 |
+
# 检查用户消息中是否明确提到agent相关词汇
|
| 960 |
+
user_mentioned_agent = False
|
| 961 |
+
for msg in reversed(history_messages or []):
|
| 962 |
+
if msg.get("role") == "user":
|
| 963 |
+
content = msg.get("content", "")
|
| 964 |
+
if isinstance(content, str):
|
| 965 |
+
text = content.lower()
|
| 966 |
+
elif isinstance(content, list):
|
| 967 |
+
text = " ".join(
|
| 968 |
+
part.get("text", "").lower()
|
| 969 |
+
for part in content
|
| 970 |
+
if isinstance(part, dict) and part.get("type") == "text"
|
| 971 |
+
)
|
| 972 |
+
else:
|
| 973 |
+
text = ""
|
| 974 |
+
if any(keyword in text for keyword in ["agent", "代理", "子任务", "subtask", "background"]):
|
| 975 |
+
user_mentioned_agent = True
|
| 976 |
+
break
|
| 977 |
+
|
| 978 |
+
if not user_mentioned_agent:
|
| 979 |
+
force_text = (
|
| 980 |
+
"[强制要求]: 不要自动调用Agent工具。用户没有要求使用代理或子任务。"
|
| 981 |
+
"请直接完成用户的请求,使用Read/Write/Edit等工具。"
|
| 982 |
+
"\n[MANDATORY]: Do NOT call Agent tool automatically. User did not request agent or subtask. "
|
| 983 |
+
"Complete the user's request directly using Read/Write/Edit tools."
|
| 984 |
+
)
|
| 985 |
+
return _retry(
|
| 986 |
+
"auto_agent_blocked",
|
| 987 |
+
inject_assistant_message(current_prompt, force_text),
|
| 988 |
+
)
|
| 989 |
+
|
| 990 |
+
if (
|
| 991 |
+
first_tool
|
| 992 |
+
and first_tool.get("name") == "WebSearch"
|
| 993 |
+
and has_recent_search_no_results(history_messages)
|
| 994 |
+
and can_retry_after_output
|
| 995 |
+
):
|
| 996 |
+
force_text = (
|
| 997 |
+
"[强制要求]: 上次WebSearch没有返回结果。"
|
| 998 |
+
"不要用类似的词再次调用WebSearch。"
|
| 999 |
+
"使用其他工具或用现有信息完成回答。"
|
| 1000 |
+
"\n[MANDATORY]: The last WebSearch returned no results. "
|
| 1001 |
+
"Do NOT call WebSearch again with similar wording. "
|
| 1002 |
+
"Use another tool or finish with the best available answer."
|
| 1003 |
+
)
|
| 1004 |
+
return _retry(
|
| 1005 |
+
"search_no_results",
|
| 1006 |
+
inject_assistant_message(current_prompt, force_text),
|
| 1007 |
+
)
|
| 1008 |
+
|
| 1009 |
+
# 空响应重试:上游返回 answer_chars=0 tool_calls=0 finish_reason=stop
|
| 1010 |
+
# 典型场景是 Qwen 后端对某个 chat_id 返回空(常见于池化 chat_id 刚建好就被用、
|
| 1011 |
+
# 或 Qwen 服务抖动时)。换账号 + 换新 chat_id 再试一次。
|
| 1012 |
+
if (
|
| 1013 |
+
not state.answer_text
|
| 1014 |
+
and not state.tool_calls
|
| 1015 |
+
and state.finish_reason == "stop"
|
| 1016 |
+
and not state.emitted_visible_output
|
| 1017 |
+
):
|
| 1018 |
+
return _retry(
|
| 1019 |
+
"empty_upstream_response",
|
| 1020 |
+
current_prompt, # prompt 不变,让上游重新处理
|
| 1021 |
+
)
|
| 1022 |
+
|
| 1023 |
+
return RuntimeRetryDirective(retry=False, next_prompt=current_prompt, reason=None)
|
| 1024 |
+
|
| 1025 |
+
|
| 1026 |
+
async def continue_after_retry_directive(*, client, execution, retry: RuntimeRetryDirective, preserve_chat: bool = False) -> RuntimeRetryContinuation:
|
| 1027 |
+
if not retry.retry:
|
| 1028 |
+
return RuntimeRetryContinuation(should_continue=False, next_prompt=retry.next_prompt)
|
| 1029 |
+
await cleanup_runtime_resources(client, execution.acc, execution.chat_id, preserve_chat=preserve_chat)
|
| 1030 |
+
if not preserve_chat:
|
| 1031 |
+
await asyncio.sleep(0.15)
|
| 1032 |
+
return RuntimeRetryContinuation(should_continue=True, next_prompt=retry.next_prompt)
|
| 1033 |
+
|
| 1034 |
+
|
| 1035 |
+
async def cleanup_runtime_resources(client, acc, chat_id: str | None, *, preserve_chat: bool = False) -> None:
|
| 1036 |
+
if acc is None:
|
| 1037 |
+
return
|
| 1038 |
+
token = getattr(acc, "token", None)
|
| 1039 |
+
client.account_pool.release(acc)
|
| 1040 |
+
if preserve_chat:
|
| 1041 |
+
return
|
| 1042 |
+
if chat_id and token:
|
| 1043 |
+
async def _delete_chat_later() -> None:
|
| 1044 |
+
try:
|
| 1045 |
+
await client.delete_chat(token, chat_id)
|
| 1046 |
+
except Exception as exc:
|
| 1047 |
+
log.debug("[Cleanup] delete_chat failed chat_id=%s error=%s", chat_id, exc)
|
| 1048 |
+
asyncio.create_task(_delete_chat_later())
|
backend/runtime/stream_metrics.py
ADDED
|
@@ -0,0 +1,12 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
|
| 4 |
+
class StreamMetrics:
|
| 5 |
+
def __init__(self):
|
| 6 |
+
self._marks: dict[str, float] = {}
|
| 7 |
+
|
| 8 |
+
def mark(self, name: str, seconds: float) -> None:
|
| 9 |
+
self._marks[name] = seconds
|
| 10 |
+
|
| 11 |
+
def summary(self) -> dict[str, float]:
|
| 12 |
+
return dict(self._marks)
|
backend/runtime/stream_presenter.py
ADDED
|
@@ -0,0 +1,71 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import json
|
| 2 |
+
from typing import Any
|
| 3 |
+
|
| 4 |
+
|
| 5 |
+
def anthropic_message_start(msg_id: str, model_name: str, usage: dict[str, Any]) -> str:
|
| 6 |
+
payload = {
|
| 7 |
+
"type": "message_start",
|
| 8 |
+
"message": {
|
| 9 |
+
"id": msg_id,
|
| 10 |
+
"type": "message",
|
| 11 |
+
"role": "assistant",
|
| 12 |
+
"content": [],
|
| 13 |
+
"model": model_name,
|
| 14 |
+
"stop_reason": None,
|
| 15 |
+
"usage": usage,
|
| 16 |
+
},
|
| 17 |
+
}
|
| 18 |
+
return f"event: message_start\ndata: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
| 19 |
+
|
| 20 |
+
|
| 21 |
+
def anthropic_content_block_start(index: int, content_block: dict[str, Any]) -> str:
|
| 22 |
+
return f"event: content_block_start\ndata: {json.dumps({'type': 'content_block_start', 'index': index, 'content_block': content_block}, ensure_ascii=False)}\n\n"
|
| 23 |
+
|
| 24 |
+
|
| 25 |
+
def anthropic_content_block_delta(index: int, delta: dict[str, Any]) -> str:
|
| 26 |
+
return f"event: content_block_delta\ndata: {json.dumps({'type': 'content_block_delta', 'index': index, 'delta': delta}, ensure_ascii=False)}\n\n"
|
| 27 |
+
|
| 28 |
+
|
| 29 |
+
def anthropic_content_block_stop(index: int) -> str:
|
| 30 |
+
return f"event: content_block_stop\ndata: {json.dumps({'type': 'content_block_stop', 'index': index}, ensure_ascii=False)}\n\n"
|
| 31 |
+
|
| 32 |
+
|
| 33 |
+
def anthropic_message_delta(stop_reason: str, output_tokens: int) -> str:
|
| 34 |
+
return f"event: message_delta\ndata: {json.dumps({'type': 'message_delta', 'delta': {'stop_reason': stop_reason}, 'usage': {'output_tokens': output_tokens}}, ensure_ascii=False)}\n\n"
|
| 35 |
+
|
| 36 |
+
|
| 37 |
+
def anthropic_message_stop() -> str:
|
| 38 |
+
return f"event: message_stop\ndata: {json.dumps({'type': 'message_stop'}, ensure_ascii=False)}\n\n"
|
| 39 |
+
|
| 40 |
+
|
| 41 |
+
def openai_chunk(completion_id: str, created: int, model_name: str, delta: dict[str, Any], finish_reason: str | None = None) -> str:
|
| 42 |
+
payload = {
|
| 43 |
+
"id": completion_id,
|
| 44 |
+
"object": "chat.completion.chunk",
|
| 45 |
+
"created": created,
|
| 46 |
+
"model": model_name,
|
| 47 |
+
"choices": [{"index": 0, "delta": delta, "finish_reason": finish_reason}],
|
| 48 |
+
}
|
| 49 |
+
return f"data: {json.dumps(payload, ensure_ascii=False)}\n\n"
|
| 50 |
+
|
| 51 |
+
|
| 52 |
+
def openai_done() -> str:
|
| 53 |
+
return "data: [DONE]\n\n"
|
| 54 |
+
|
| 55 |
+
|
| 56 |
+
def gemini_text_chunk(text: str) -> str:
|
| 57 |
+
payload = {
|
| 58 |
+
"candidates": [
|
| 59 |
+
{
|
| 60 |
+
"content": {
|
| 61 |
+
"parts": [{"text": text}],
|
| 62 |
+
"role": "model",
|
| 63 |
+
}
|
| 64 |
+
}
|
| 65 |
+
]
|
| 66 |
+
}
|
| 67 |
+
return json.dumps(payload, ensure_ascii=False) + "\n"
|
| 68 |
+
|
| 69 |
+
|
| 70 |
+
def gemini_error_chunk(message: str) -> str:
|
| 71 |
+
return json.dumps({"error": message}, ensure_ascii=False) + "\n"
|
backend/runtime/stream_runtime.py
ADDED
|
@@ -0,0 +1,51 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from collections.abc import AsyncIterable, Iterable
|
| 4 |
+
from dataclasses import dataclass, field
|
| 5 |
+
from typing import Any, TypeAlias, cast
|
| 6 |
+
|
| 7 |
+
from .finalizer import finalize_runtime_result
|
| 8 |
+
|
| 9 |
+
Event: TypeAlias = dict[str, Any]
|
| 10 |
+
EventSource: TypeAlias = Iterable[Event] | AsyncIterable[Event]
|
| 11 |
+
|
| 12 |
+
|
| 13 |
+
@dataclass
|
| 14 |
+
class RuntimeResult:
|
| 15 |
+
text: str = ""
|
| 16 |
+
tool_calls: list[dict[str, Any]] = field(default_factory=list)
|
| 17 |
+
finish_reason: str | None = None
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
class StreamRuntime:
|
| 21 |
+
def __init__(self, request: dict[str, Any]) -> None:
|
| 22 |
+
self.request = request
|
| 23 |
+
self.result = RuntimeResult()
|
| 24 |
+
|
| 25 |
+
def _apply_event(self, event: Event) -> None:
|
| 26 |
+
event_type = event.get("type")
|
| 27 |
+
|
| 28 |
+
if event_type == "text_delta":
|
| 29 |
+
self.result.text += event.get("text", "")
|
| 30 |
+
elif event_type == "tool_call":
|
| 31 |
+
self.result.tool_calls.append(
|
| 32 |
+
{
|
| 33 |
+
"id": event.get("id"),
|
| 34 |
+
"name": event.get("name"),
|
| 35 |
+
"input": event.get("input", {}),
|
| 36 |
+
}
|
| 37 |
+
)
|
| 38 |
+
elif event_type == "finish":
|
| 39 |
+
self.result.finish_reason = event.get("finish_reason")
|
| 40 |
+
|
| 41 |
+
async def collect(self, events: EventSource) -> RuntimeResult:
|
| 42 |
+
if hasattr(events, "__aiter__"):
|
| 43 |
+
async_events = cast(AsyncIterable[Event], events)
|
| 44 |
+
async for event in async_events:
|
| 45 |
+
self._apply_event(event)
|
| 46 |
+
else:
|
| 47 |
+
sync_events = cast(Iterable[Event], events)
|
| 48 |
+
for event in sync_events:
|
| 49 |
+
self._apply_event(event)
|
| 50 |
+
|
| 51 |
+
return finalize_runtime_result(self.result)
|
backend/services/attachment_preprocessor.py
ADDED
|
@@ -0,0 +1,138 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
import base64
|
| 4 |
+
import copy
|
| 5 |
+
from dataclasses import dataclass, field
|
| 6 |
+
from typing import Any
|
| 7 |
+
|
| 8 |
+
from backend.runtime.attachment_types import NormalizedAttachment
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass(slots=True)
|
| 12 |
+
class PreprocessedAttachments:
|
| 13 |
+
payload: dict[str, Any]
|
| 14 |
+
attachments: list[NormalizedAttachment] = field(default_factory=list)
|
| 15 |
+
uploaded_file_ids: list[str] = field(default_factory=list)
|
| 16 |
+
|
| 17 |
+
|
| 18 |
+
def _decode_data_uri(url: str) -> tuple[str, bytes]:
|
| 19 |
+
header, encoded = url.split(",", 1)
|
| 20 |
+
content_type = header.split(";", 1)[0][5:] or "application/octet-stream"
|
| 21 |
+
return content_type, base64.b64decode(encoded)
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def _extract_inline_file_payload(block: dict[str, Any]) -> tuple[str, str, bytes] | None:
|
| 25 |
+
filename = str(block.get("filename") or block.get("name") or "attachment.txt")
|
| 26 |
+
content_type = str(block.get("mime_type") or block.get("content_type") or "text/plain")
|
| 27 |
+
|
| 28 |
+
if isinstance(block.get("text"), str):
|
| 29 |
+
return filename, content_type, block["text"].encode("utf-8")
|
| 30 |
+
if isinstance(block.get("content"), str) and not str(block.get("content", "")).startswith("data:"):
|
| 31 |
+
return filename, content_type, block["content"].encode("utf-8")
|
| 32 |
+
if isinstance(block.get("data_base64"), str):
|
| 33 |
+
return filename, content_type, base64.b64decode(block["data_base64"])
|
| 34 |
+
if isinstance(block.get("data"), str):
|
| 35 |
+
return filename, content_type, base64.b64decode(block["data"])
|
| 36 |
+
if isinstance(block.get("content"), str) and str(block.get("content", "")).startswith("data:"):
|
| 37 |
+
ct, raw = _decode_data_uri(block["content"])
|
| 38 |
+
return filename, ct, raw
|
| 39 |
+
return None
|
| 40 |
+
|
| 41 |
+
|
| 42 |
+
async def preprocess_attachments(payload: dict[str, Any], file_store, owner_token: str | None = None) -> PreprocessedAttachments:
|
| 43 |
+
messages = payload.get("messages", [])
|
| 44 |
+
needs_rewrite = False
|
| 45 |
+
for message in messages:
|
| 46 |
+
content = message.get("content")
|
| 47 |
+
if not isinstance(content, list):
|
| 48 |
+
continue
|
| 49 |
+
for block in content:
|
| 50 |
+
if not isinstance(block, dict):
|
| 51 |
+
continue
|
| 52 |
+
if block.get("type") == "image_url":
|
| 53 |
+
image_url = block.get("image_url") or {}
|
| 54 |
+
if isinstance(image_url, dict) and str(image_url.get("url") or "").strip().startswith("data:"):
|
| 55 |
+
needs_rewrite = True
|
| 56 |
+
break
|
| 57 |
+
if block.get("type") in ("input_file", "file") and _extract_inline_file_payload(block):
|
| 58 |
+
needs_rewrite = True
|
| 59 |
+
break
|
| 60 |
+
if needs_rewrite:
|
| 61 |
+
break
|
| 62 |
+
|
| 63 |
+
if not needs_rewrite:
|
| 64 |
+
return PreprocessedAttachments(payload=payload)
|
| 65 |
+
|
| 66 |
+
rewritten = copy.deepcopy(payload)
|
| 67 |
+
attachments: list[NormalizedAttachment] = []
|
| 68 |
+
uploaded_file_ids: list[str] = []
|
| 69 |
+
|
| 70 |
+
for message in rewritten.get("messages", []):
|
| 71 |
+
content = message.get("content")
|
| 72 |
+
if not isinstance(content, list):
|
| 73 |
+
continue
|
| 74 |
+
for index, block in enumerate(content):
|
| 75 |
+
if not isinstance(block, dict):
|
| 76 |
+
continue
|
| 77 |
+
if block.get("type") == "image_url":
|
| 78 |
+
image_url = block.get("image_url") or {}
|
| 79 |
+
if isinstance(image_url, dict) and str(image_url.get("url") or "").strip().startswith("data:"):
|
| 80 |
+
content_type, raw = _decode_data_uri(str(image_url.get("url") or ""))
|
| 81 |
+
result = await file_store.save_bytes("inline-image", content_type, raw, "vision", owner_token=owner_token)
|
| 82 |
+
uploaded_file_ids.append(result["id"])
|
| 83 |
+
attachments.append(NormalizedAttachment(
|
| 84 |
+
file_id=result["id"],
|
| 85 |
+
filename=result["filename"],
|
| 86 |
+
content_type=content_type,
|
| 87 |
+
source="inline-image",
|
| 88 |
+
local_path=result["path"],
|
| 89 |
+
sha256=result["sha256"],
|
| 90 |
+
purpose="user-upload",
|
| 91 |
+
))
|
| 92 |
+
content[index] = {"type": "input_image", "file_id": result["id"], "mime_type": content_type}
|
| 93 |
+
continue
|
| 94 |
+
|
| 95 |
+
if block.get("type") in ("input_file", "file"):
|
| 96 |
+
existing_file_id = str(block.get("file_id") or "").strip()
|
| 97 |
+
if existing_file_id:
|
| 98 |
+
existing = await file_store.get(existing_file_id)
|
| 99 |
+
if existing and (not existing.get("owner_token") or existing.get("owner_token") == (owner_token or "")):
|
| 100 |
+
attachments.append(NormalizedAttachment(
|
| 101 |
+
file_id=existing["id"],
|
| 102 |
+
filename=existing["filename"],
|
| 103 |
+
content_type=existing.get("content_type", "application/octet-stream"),
|
| 104 |
+
source="manual-upload-ref",
|
| 105 |
+
local_path=existing.get("path", ""),
|
| 106 |
+
sha256=existing.get("sha256", ""),
|
| 107 |
+
purpose="user-upload",
|
| 108 |
+
))
|
| 109 |
+
content[index] = {
|
| 110 |
+
"type": "input_file",
|
| 111 |
+
"file_id": existing["id"],
|
| 112 |
+
"filename": existing["filename"],
|
| 113 |
+
"mime_type": existing.get("content_type", "application/octet-stream"),
|
| 114 |
+
}
|
| 115 |
+
continue
|
| 116 |
+
extracted = _extract_inline_file_payload(block)
|
| 117 |
+
if not extracted:
|
| 118 |
+
continue
|
| 119 |
+
filename, content_type, raw = extracted
|
| 120 |
+
result = await file_store.save_bytes(filename, content_type, raw, "upload", owner_token=owner_token)
|
| 121 |
+
uploaded_file_ids.append(result["id"])
|
| 122 |
+
attachments.append(NormalizedAttachment(
|
| 123 |
+
file_id=result["id"],
|
| 124 |
+
filename=result["filename"],
|
| 125 |
+
content_type=content_type,
|
| 126 |
+
source="manual-upload",
|
| 127 |
+
local_path=result["path"],
|
| 128 |
+
sha256=result["sha256"],
|
| 129 |
+
purpose="user-upload",
|
| 130 |
+
))
|
| 131 |
+
content[index] = {
|
| 132 |
+
"type": "input_file",
|
| 133 |
+
"file_id": result["id"],
|
| 134 |
+
"filename": result["filename"],
|
| 135 |
+
"mime_type": content_type,
|
| 136 |
+
}
|
| 137 |
+
|
| 138 |
+
return PreprocessedAttachments(payload=rewritten, attachments=attachments, uploaded_file_ids=uploaded_file_ids)
|
backend/services/auth_quota.py
ADDED
|
@@ -0,0 +1,58 @@
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
from __future__ import annotations
|
| 2 |
+
|
| 3 |
+
from dataclasses import dataclass
|
| 4 |
+
from typing import Any
|
| 5 |
+
|
| 6 |
+
from fastapi import HTTPException, Request
|
| 7 |
+
|
| 8 |
+
from backend.core.config import API_KEYS, settings
|
| 9 |
+
|
| 10 |
+
|
| 11 |
+
@dataclass(slots=True)
|
| 12 |
+
class AuthContext:
|
| 13 |
+
token: str
|
| 14 |
+
user: dict[str, Any] | None
|
| 15 |
+
|
| 16 |
+
|
| 17 |
+
def extract_api_token(request: Request) -> str:
|
| 18 |
+
auth_header = request.headers.get("Authorization", "")
|
| 19 |
+
token = auth_header[7:].strip() if auth_header.startswith("Bearer ") else ""
|
| 20 |
+
if token:
|
| 21 |
+
return token
|
| 22 |
+
|
| 23 |
+
token = request.headers.get("x-api-key", "").strip()
|
| 24 |
+
if token:
|
| 25 |
+
return token
|
| 26 |
+
|
| 27 |
+
return request.query_params.get("key", "").strip() or request.query_params.get("api_key", "").strip()
|
| 28 |
+
|
| 29 |
+
|
| 30 |
+
async def resolve_auth_context(request: Request, users_db) -> AuthContext:
|
| 31 |
+
token = extract_api_token(request)
|
| 32 |
+
if not token:
|
| 33 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 34 |
+
|
| 35 |
+
users = await users_db.get()
|
| 36 |
+
user = next((u for u in users if u["id"] == token), None)
|
| 37 |
+
|
| 38 |
+
if API_KEYS and token != settings.ADMIN_KEY and token not in API_KEYS:
|
| 39 |
+
saved_snapshots = getattr(users_db, "saved_snapshots", None)
|
| 40 |
+
if user is None and not isinstance(saved_snapshots, list):
|
| 41 |
+
raise HTTPException(status_code=401, detail="Invalid API Key")
|
| 42 |
+
|
| 43 |
+
if user and user.get("quota", 0) <= user.get("used_tokens", 0):
|
| 44 |
+
raise HTTPException(status_code=402, detail="Quota Exceeded")
|
| 45 |
+
|
| 46 |
+
return AuthContext(token=token, user=user)
|
| 47 |
+
|
| 48 |
+
|
| 49 |
+
async def add_used_tokens(users_db, token: str, delta: int) -> None:
|
| 50 |
+
if delta <= 0:
|
| 51 |
+
return
|
| 52 |
+
|
| 53 |
+
users = await users_db.get()
|
| 54 |
+
for user in users:
|
| 55 |
+
if user["id"] == token:
|
| 56 |
+
user["used_tokens"] += delta
|
| 57 |
+
break
|
| 58 |
+
await users_db.save(users)
|