ZyphrZero commited on
Commit
c4a7c2d
·
unverified ·
2 Parent(s): b7da053 c6f78e9

Merge pull request #9 from ZyphrZero/dev

Browse files
.env.example CHANGED
@@ -2,36 +2,38 @@
2
  # 复制此文件为 .env 并根据需要修改配置值
3
 
4
  # ========== API 基础配置 ==========
5
- # Z.ai API 端点地址
6
- API_ENDPOINT=https://chat.z.ai/api/chat/completions
7
-
8
  # 客户端认证密钥(您自定义的 API 密钥,用于客户端访问本服务)
9
  AUTH_TOKEN=sk-your-api-key
10
 
11
  # 跳过客户端认证(仅开发环境使用)
12
  SKIP_AUTH_TOKEN=false
13
 
14
- # Z.ai 备用访问令牌(当匿名模式失败时使用)
15
- # 注意:这是用于访问 Z.ai 服务的令牌,不是客户端认证密钥
16
- BACKUP_TOKEN=eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMxNmJjYjQ4LWZmMmYtNGExNS04NTNkLWYyYTI5YjY3ZmYwZiIsImVtYWlsIjoiR3Vlc3QtMTc1NTg0ODU4ODc4OEBndWVzdC5jb20ifQ.PktllDySS3trlyuFpTeIZf-7hl8Qu1qYF3BxjgIul0BrNux2nX9hVzIjthLXKMWAf9V0qM8Vm_iyDqkjPGsaiQ
 
 
 
 
 
 
 
 
 
 
 
 
17
 
18
  # ========== 服务器配置 ==========
19
  # 服务监听端口
20
  LISTEN_PORT=8080
21
 
22
- # 调试日志开关
23
  DEBUG_LOGGING=true
24
 
25
- # ========== 功能配置 ==========
26
- # 思考内容处理策略
27
- # think: 转换为 <span> 标签(OpenAI 兼容)
28
- # strip: 移除思考内容
29
- # raw: 保留原始格式
30
- THINKING_PROCESSING=think
31
-
32
- # 匿名模式开关(推荐启用)
33
  # true: 自动从 Z.ai 获取临时访问令牌,避免对话历史共享
34
- # false: 使用固定令牌 BACKUP_TOKEN
35
  ANONYMOUS_MODE=true
36
 
37
  # Function Call 功能开关
@@ -39,3 +41,10 @@ TOOL_SUPPORT=true
39
 
40
  # 工具调用扫描限制(字符数)
41
  SCAN_LIMIT=200000
 
 
 
 
 
 
 
 
2
  # 复制此文件为 .env 并根据需要修改配置值
3
 
4
  # ========== API 基础配置 ==========
 
 
 
5
  # 客户端认证密钥(您自定义的 API 密钥,用于客户端访问本服务)
6
  AUTH_TOKEN=sk-your-api-key
7
 
8
  # 跳过客户端认证(仅开发环境使用)
9
  SKIP_AUTH_TOKEN=false
10
 
11
+ # ========== Token池配置 ==========
12
+ # Token失败阈值(失败多少次后标记为不可用)
13
+ TOKEN_FAILURE_THRESHOLD=3
14
+
15
+ # Token恢复超时时间(秒,失败token在此时间后重新尝试)
16
+ TOKEN_RECOVERY_TIMEOUT=1800
17
+
18
+ # Token健康检查间隔(秒,定期检查token状态)
19
+ TOKEN_HEALTH_CHECK_INTERVAL=300
20
+
21
+ # Z.ai 认证token配置(当匿名模式失败时使用)
22
+ #
23
+ # 使用独立的token文件配置
24
+ # 在项目根目录创建 tokens.txt 文件,每行一个token或逗号分隔
25
+ AUTH_TOKENS_FILE=tokens.txt
26
 
27
  # ========== 服务器配置 ==========
28
  # 服务监听端口
29
  LISTEN_PORT=8080
30
 
31
+ # 调试日志
32
  DEBUG_LOGGING=true
33
 
34
+ # 匿名用户模式
35
+ # false: 使用认证用户令牌
 
 
 
 
 
 
36
  # true: 自动从 Z.ai 获取临时访问令牌,避免对话历史共享
 
37
  ANONYMOUS_MODE=true
38
 
39
  # Function Call 功能开关
 
41
 
42
  # 工具调用扫描限制(字符数)
43
  SCAN_LIMIT=200000
44
+
45
+ # ========== 错误码400处理 ==========
46
+
47
+ # 重试次数
48
+ MAX_RETRIES=5
49
+ # 初始重试延迟
50
+ RETRY_DELAY=1
.gitignore CHANGED
@@ -13,6 +13,7 @@ main.onefile-build/
13
  *report.xml
14
  *.yaml
15
  logs/
 
16
 
17
  # AI Toolset
18
  .augment/
 
13
  *report.xml
14
  *.yaml
15
  logs/
16
+ backup/
17
 
18
  # AI Toolset
19
  .augment/
README.md CHANGED
@@ -1,30 +1,34 @@
1
  # Z.AI OpenAI API 代理服务
2
 
3
  ![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
4
- ![Python: 3.8+](https://img.shields.io/badge/python-3.8+-green.svg)
5
  ![FastAPI](https://img.shields.io/badge/framework-FastAPI-009688.svg)
6
- ![Version: 1.2.0](https://img.shields.io/badge/version-1.2.0-brightgreen.svg)
7
 
8
- 轻量级 OpenAI API 兼容代理服务,通过 Claude Code Router 接入 Z.AI,支持 GLM-4.5 系列模型的完整功能。
 
 
9
 
10
  ## ✨ 核心特性
11
 
12
  - 🔌 **完全兼容 OpenAI API** - 无缝集成现有应用
13
  - 🤖 **Claude Code 支持** - 通过 Claude Code Router 接入 Claude Code (**CCR 工具请升级到 v1.0.47 以上**)
14
  - 🚀 **高性能流式响应** - Server-Sent Events (SSE) 支持
15
- - 🛠️ **增强工具调用** - 改进的 Function Call 实现
16
  - 🧠 **思考模式支持** - 智能处理模型推理过程
17
  - 🔍 **搜索模型集成** - GLM-4.5-Search 网络搜索能力
18
  - 🐳 **Docker 部署** - 一键容器化部署
19
  - 🛡️ **会话隔离** - 匿名模式保护隐私
20
  - 🔧 **灵活配置** - 环境变量灵活配置
21
  - 📊 **多模型映射** - 智能上游模型路由
 
 
22
 
23
  ## 🚀 快速开始
24
 
25
  ### 环境要求
26
 
27
- - Python 3.8+
28
  - pip 或 uv (推荐)
29
 
30
  ### 安装运行
@@ -44,7 +48,9 @@ pip install -r requirements.txt -i https://pypi.tuna.tsinghua.edu.cn/simple
44
  python main.py
45
  ```
46
 
47
- 服务启动后访问:http://localhost:8080/docs
 
 
48
 
49
  ### 基础使用
50
 
@@ -142,21 +148,51 @@ for chunk in response:
142
  | 变量名 | 默认值 | 说明 |
143
  | --------------------- | ----------------------------------------- | ---------------------- |
144
  | `AUTH_TOKEN` | `sk-your-api-key` | 客户端认证密钥 |
145
- | `API_ENDPOINT` | `https://chat.z.ai/api/chat/completions` | 上游 API 地址 |
146
  | `LISTEN_PORT` | `8080` | 服务监听端口 |
147
  | `DEBUG_LOGGING` | `true` | 调试日志开关 |
148
- | `THINKING_PROCESSING` | `think` | 思考内容处理策略 |
149
- | `ANONYMOUS_MODE` | `true` | 匿名模式开关 |
150
  | `TOOL_SUPPORT` | `true` | Function Call 功能开关 |
151
  | `SKIP_AUTH_TOKEN` | `false` | 跳过认证令牌验证 |
152
  | `SCAN_LIMIT` | `200000` | 扫描限制 |
153
- | `BACKUP_TOKEN` | `eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9...` | Z.ai 固定访问令牌 |
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
154
 
155
- ### 思考内容处理策略
 
 
 
 
 
 
 
 
 
 
 
156
 
157
- - `think` - 转换为 `<thinking>` 标签(OpenAI 兼容)
158
- - `strip` - 移除思考内容
159
- - `raw` - 保留原始格式
160
 
161
  ## 🎯 使用场景
162
 
@@ -203,6 +239,12 @@ if response.choices[0].message.tool_calls:
203
  **Q: 如何获取 AUTH_TOKEN?**
204
  A: `AUTH_TOKEN` 为自己自定义的 api key,在环境变量中配置,需要保证客户端与服务端一致。
205
 
 
 
 
 
 
 
206
  **Q: 如何通过 Claude Code 使用本服务?**
207
 
208
  A: 创建 [zai.js](https://gist.githubusercontent.com/musistudio/b35402d6f9c95c64269c7666b8405348/raw/f108d66fa050f308387938f149a2b14a295d29e9/gistfile1.txt) 这个 ccr 插件放在`./.claude-code-router/plugins`目录下,配置 `./.claude-code-router/config.json` 指向本服务地址,使用 `AUTH_TOKEN` 进行认证。
@@ -287,32 +329,25 @@ A: 通过环境变量配置,推荐使用 `.env` 文件。
287
 
288
  要使用完整的多模态功能,需要获取正式的 Z.ai API Token:
289
 
290
- ### 方式 1: 通过 Z.ai 网站
291
-
292
- 1. 访问 [Z.ai 官网](https://chat.z.ai)
293
- 2. 注册账户并登录,进入 [Z.ai API Keys](https://z.ai/manage-apikey/apikey-list) 设置页面,在该页面设置 _**个人 API Token**_
294
- 3. 将 Token 放置在 `BACKUP_TOKEN` 环境变量中
295
-
296
- ### 方式 2: 浏览器开发者工具(临时方案)
297
-
298
  1. 打开 [Z.ai 聊天界面](https://chat.z.ai)
299
  2. 按 F12 打开开发者工具
300
  3. 切换到 "Application" 或 "存储" 标签
301
  4. 查看 Local Storage 中的认证 token
302
  5. 复制 token 值设置为环境变量
303
 
304
- > ⚠️ **注意**: 方式 2 获取的 token 可能有时效性,建议使用方式 1 获取长期有效的 API Token
305
- > ❗ **重要提示**: 多模态模型需要**官方 Z.ai API 非匿名 Token**,匿名 token 不支持多媒体处理。
306
 
307
  ## 🛠️ 技术栈
308
 
309
  | 组件 | 技术 | 版本 | 说明 |
310
  | --------------- | --------------------------------------------------------------------------------- | ------- | ------------------------------------------ |
311
- | **Web 框架** | [FastAPI](https://fastapi.tiangolo.com/) | 0.104.1 | 高性能异步 Web 框架,支持自动 API 文档生成 |
312
  | **ASGI 服务器** | [Granian](https://github.com/emmett-framework/granian) | 2.5.2 | 基于 Rust 的高性能 ASGI 服务器,支持热重载 |
313
- | **HTTP 客户端** | [Requests](https://requests.readthedocs.io/) | 2.32.5 | 简洁易用的 HTTP 库,用于上游 API 调用 |
314
  | **数据验证** | [Pydantic](https://pydantic.dev/) | 2.11.7 | 类型安全的数据验证与序列化 |
315
  | **配置管理** | [Pydantic Settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) | 2.10.1 | 基于 Pydantic 的配置管理 |
 
 
316
 
317
  ## 🏗️ 技术架构
318
 
@@ -338,27 +373,27 @@ A: 通过环境变量配置,推荐使用 `.env` 文件。
338
 
339
  ```
340
  z.ai2api_python/
341
- ├── app/
342
- │ ├── core/
343
- │ │ ├── __init__.py
344
- │ │ ├── config.py # 配置管理
345
- │ │ ├── openai.py # OpenAI API 实现
346
- │ └── response_handlers.py # 响应处理器
347
- ├── models/
348
- │ ├── __init__.py
349
- │ └── schemas.py # Pydantic 模型定义
350
- ├── utils/
351
- ├── __init__.py
352
- │ ├── helpers.py # 辅助函数
353
- │ │ ├── tools.py # 增强工具调用处理
354
- │ │ └── sse_parser.py # SSE 流式解析器
355
- └── __init__.py
356
- ├── tests/ # 单元测试
357
- ├── deploy/ # Docker 部署配置
358
- ├── main.py # FastAPI 应用入口
359
- ├── requirements.txt # Python 依赖
360
- ├── .env.example # 环境变量示例
361
- └── README.md # 项目文档
362
  ```
363
 
364
  ## ⭐ Star History
 
1
  # Z.AI OpenAI API 代理服务
2
 
3
  ![License: MIT](https://img.shields.io/badge/license-MIT-blue.svg)
4
+ ![Python: 3.9-3.12](https://img.shields.io/badge/python-3.9--3.12-green.svg)
5
  ![FastAPI](https://img.shields.io/badge/framework-FastAPI-009688.svg)
6
+ ![Version: 0.1.0](https://img.shields.io/badge/version-0.1.0-brightgreen.svg)
7
 
8
+ > 🎯 **项目愿景**:提供完全兼容 OpenAI API Z.AI 代理服务,让用户无需修改现有代码即可接入 GLM-4.5 系列模型。
9
+
10
+ 轻量级、高性能的 OpenAI API 兼容代理服务,通过 Claude Code Router 接入 Z.AI,支持 GLM-4.5 系列模型的完整功能。
11
 
12
  ## ✨ 核心特性
13
 
14
  - 🔌 **完全兼容 OpenAI API** - 无缝集成现有应用
15
  - 🤖 **Claude Code 支持** - 通过 Claude Code Router 接入 Claude Code (**CCR 工具请升级到 v1.0.47 以上**)
16
  - 🚀 **高性能流式响应** - Server-Sent Events (SSE) 支持
17
+ - 🛠️ **增强工具调用** - 改进的 Function Call 实现,支持复杂工具链
18
  - 🧠 **思考模式支持** - 智能处理模型推理过程
19
  - 🔍 **搜索模型集成** - GLM-4.5-Search 网络搜索能力
20
  - 🐳 **Docker 部署** - 一键容器化部署
21
  - 🛡️ **会话隔离** - 匿名模式保护隐私
22
  - 🔧 **灵活配置** - 环境变量灵活配置
23
  - 📊 **多模型映射** - 智能上游模型路由
24
+ - 🔄 **Token 池管理** - 自动轮询、容错恢复、动态更新
25
+ - 🛡️ **错误处理** - 完善的异常捕获和重试机制
26
 
27
  ## 🚀 快速开始
28
 
29
  ### 环境要求
30
 
31
+ - Python 3.9-3.12
32
  - pip 或 uv (推荐)
33
 
34
  ### 安装运行
 
48
  python main.py
49
  ```
50
 
51
+ > 服务启动后访问接口文档:http://localhost:8080/docs
52
+ > 💡 **提示**:默认端口为 8080,可通过环境变量 `LISTEN_PORT` 修改
53
+ > ⚠️ **注意**:请勿将 `AUTH_TOKEN` 泄露给其他人,请使用 `AUTH_TOKENS` 配置多个认证令牌
54
 
55
  ### 基础使用
56
 
 
148
  | 变量名 | 默认值 | 说明 |
149
  | --------------------- | ----------------------------------------- | ---------------------- |
150
  | `AUTH_TOKEN` | `sk-your-api-key` | 客户端认证密钥 |
 
151
  | `LISTEN_PORT` | `8080` | 服务监听端口 |
152
  | `DEBUG_LOGGING` | `true` | 调试日志开关 |
153
+ | `ANONYMOUS_MODE` | `true` | 匿名用户模式开关 |
 
154
  | `TOOL_SUPPORT` | `true` | Function Call 功能开关 |
155
  | `SKIP_AUTH_TOKEN` | `false` | 跳过认证令牌验证 |
156
  | `SCAN_LIMIT` | `200000` | 扫描限制 |
157
+ | `AUTH_TOKENS_FILE` | `tokens.txt` | 认证token文件路径 |
158
+
159
+ > 💡 详细配置请查看 `.env.example` 文件
160
+
161
+ ## 🔄 Token池机制
162
+
163
+ ### 功能特性
164
+
165
+ - **负载均衡**:轮询使用多个auth token,分散请求负载
166
+ - **自动容错**:token失败时自动切换到下一个可用token
167
+ - **健康监控**:基于Z.AI API的role字段精确验证token类型
168
+ - **自动恢复**:失败token在超时后自动重新尝试
169
+ - **动态管理**:支持运行时更新token池
170
+ - **智能去重**:自动检测和去除重复token
171
+ - **类型验证**:只接受认证用户token (role: "user"),拒绝匿名token (role: "guest")
172
+
173
+ ### Token配置方式
174
+
175
+ 创建 `tokens.txt` 文件,支持多种格式的混合使用:
176
+ 1. 每行一个token(换行分隔)
177
+ 2. 逗号分隔的token
178
+ 3. 混合格式(同时支持换行和逗号分隔)
179
+
180
+ ## 监控API
181
 
182
+ ```bash
183
+ # 查看token池状态
184
+ curl http://localhost:8080/v1/token-pool/status
185
+
186
+ # 手动健康检查
187
+ curl -X POST http://localhost:8080/v1/token-pool/health-check
188
+
189
+ # 动态更新token池
190
+ curl -X POST http://localhost:8080/v1/token-pool/update \
191
+ -H "Content-Type: application/json" \
192
+ -d '["new_token1", "new_token2"]'
193
+ ```
194
 
195
+ 详细文档请参考:[Token池功能说明](TOKEN_POOL_README.md)
 
 
196
 
197
  ## 🎯 使用场景
198
 
 
239
  **Q: 如何获取 AUTH_TOKEN?**
240
  A: `AUTH_TOKEN` 为自己自定义的 api key,在环境变量中配置,需要保证客户端与服务端一致。
241
 
242
+ **Q: 遇到 "Illegal header value b'Bearer '" 错误怎么办?**
243
+ A: 这通常是因为 Token 获取失败导致的。请检查:
244
+ - 匿名模式是否正确配置(`ANONYMOUS_MODE=true`)
245
+ - Token 文件是否存在且格式正确(`tokens.txt`)
246
+ - 网络连接是否正常,能否访问 Z.AI API
247
+
248
  **Q: 如何通过 Claude Code 使用本服务?**
249
 
250
  A: 创建 [zai.js](https://gist.githubusercontent.com/musistudio/b35402d6f9c95c64269c7666b8405348/raw/f108d66fa050f308387938f149a2b14a295d29e9/gistfile1.txt) 这个 ccr 插件放在`./.claude-code-router/plugins`目录下,配置 `./.claude-code-router/config.json` 指向本服务地址,使用 `AUTH_TOKEN` 进行认证。
 
329
 
330
  要使用完整的多模态功能,需要获取正式的 Z.ai API Token:
331
 
 
 
 
 
 
 
 
 
332
  1. 打开 [Z.ai 聊天界面](https://chat.z.ai)
333
  2. 按 F12 打开开发者工具
334
  3. 切换到 "Application" 或 "存储" 标签
335
  4. 查看 Local Storage 中的认证 token
336
  5. 复制 token 值设置为环境变量
337
 
338
+ > **重要提示**: 获取的 token 可能有时效性,多模态模型需要**官方 Z.ai API 非匿名 Token**,匿名 token 不支持多媒体处理
 
339
 
340
  ## 🛠️ 技术栈
341
 
342
  | 组件 | 技术 | 版本 | 说明 |
343
  | --------------- | --------------------------------------------------------------------------------- | ------- | ------------------------------------------ |
344
+ | **Web 框架** | [FastAPI](https://fastapi.tiangolo.com/) | 0.116.1 | 高性能异步 Web 框架,支持自动 API 文档生成 |
345
  | **ASGI 服务器** | [Granian](https://github.com/emmett-framework/granian) | 2.5.2 | 基于 Rust 的高性能 ASGI 服务器,支持热重载 |
346
+ | **HTTP 客户端** | [HTTPX](https://www.python-httpx.org/) / [Requests](https://requests.readthedocs.io/) | 0.27.0 / 2.32.5 | 异步/同步 HTTP 库,用于上游 API 调用 |
347
  | **数据验证** | [Pydantic](https://pydantic.dev/) | 2.11.7 | 类型安全的数据验证与序列化 |
348
  | **配置管理** | [Pydantic Settings](https://docs.pydantic.dev/latest/concepts/pydantic_settings/) | 2.10.1 | 基于 Pydantic 的配置管理 |
349
+ | **日志系统** | [Loguru](https://loguru.readthedocs.io/) | 0.7.3 | 高性能结构化日志库 |
350
+ | **用户代理** | [Fake UserAgent](https://pypi.org/project/fake-useragent/) | 2.2.0 | 动态用户代理生成 |
351
 
352
  ## 🏗️ 技术架构
353
 
 
373
 
374
  ```
375
  z.ai2api_python/
376
+ ├── app/ # 主应用模块
377
+ │ ├── core/ # 核心模块
378
+ │ │ ├── config.py # 配置管理(Pydantic Settings)
379
+ │ │ ├── openai.py # OpenAI API 兼容层
380
+ │ │ └── zai_transformer.py # Z.AI 请求/响应转换器
381
+ ├── models/ # 数据模型
382
+ │ └── schemas.py # Pydantic 数据模型
383
+ └── utils/ # 工具模块
384
+ ├── logger.py # Loguru 日志系统
385
+ ├── reload_config.py # 热重载配置
386
+ ├── sse_tool_handler.py # SSE 工具调用处理器
387
+ └── token_pool.py # Token 池管理
388
+ ├── tests/ # 测试文件
389
+ ├── deploy/ # 部署配置
390
+ ├── Dockerfile # Docker 镜像构建
391
+ │ └── docker-compose.yml # 容器编排
392
+ ├── main.py # FastAPI 应用入口
393
+ ├── requirements.txt # 依赖清单
394
+ ├── pyproject.toml # 项目配置
395
+ ├── tokens.txt.example # Token 配置文件
396
+ └── .env.example # 环境变量示例
397
  ```
398
 
399
  ## ⭐ Star History
app/__init__.py CHANGED
@@ -1,6 +1,5 @@
1
- """
2
- Application package initialization
3
- """
4
 
5
  from app import core, models, utils
6
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
  from app import core, models, utils
5
 
app/core/__init__.py CHANGED
@@ -1,7 +1,6 @@
1
- """
2
- Core module initialization
3
- """
4
 
5
- from app.core import config, response_handlers, openai
6
 
7
- __all__ = ["config", "response_handlers", "openai"]
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
+ from app.core import config, zai_transformer, openai
5
 
6
+ __all__ = ["config", "zai_transformer", "openai"]
app/core/config.py CHANGED
@@ -1,37 +1,124 @@
1
- """
2
- FastAPI application configuration module
3
- """
4
 
5
  import os
6
- from typing import Dict, Optional
7
  from pydantic_settings import BaseSettings
 
8
 
9
 
10
  class Settings(BaseSettings):
11
  """Application settings"""
12
-
13
  # API Configuration
14
- API_ENDPOINT: str = os.getenv("API_ENDPOINT", "https://chat.z.ai/api/chat/completions")
15
  AUTH_TOKEN: str = os.getenv("AUTH_TOKEN", "sk-your-api-key")
16
- BACKUP_TOKEN: str = os.getenv("BACKUP_TOKEN", "eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMxNmJjYjQ4LWZmMmYtNGExNS04NTNkLWYyYTI5YjY3ZmYwZiIsImVtYWlsIjoiR3Vlc3QtMTc1NTg0ODU4ODc4OEBndWVzdC5jb20ifQ.PktllDySS3trlyuFpTeIZf-7hl8Qu1qYF3BxjgIul0BrNux2nX9hVzIjthLXKMWAf9V0qM8Vm_iyDqkjPGsaiQ")
17
-
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
18
  # Model Configuration
19
  PRIMARY_MODEL: str = os.getenv("PRIMARY_MODEL", "GLM-4.5")
20
  THINKING_MODEL: str = os.getenv("THINKING_MODEL", "GLM-4.5-Thinking")
21
  SEARCH_MODEL: str = os.getenv("SEARCH_MODEL", "GLM-4.5-Search")
22
  AIR_MODEL: str = os.getenv("AIR_MODEL", "GLM-4.5-Air")
23
-
24
  # Server Configuration
25
  LISTEN_PORT: int = int(os.getenv("LISTEN_PORT", "8080"))
26
  DEBUG_LOGGING: bool = os.getenv("DEBUG_LOGGING", "true").lower() == "true"
27
-
28
- # Feature Configuration
29
- THINKING_PROCESSING: str = os.getenv("THINKING_PROCESSING", "think") # strip: 去除<details>标签;think: 转为<span>标签;raw: 保留原样
30
  ANONYMOUS_MODE: bool = os.getenv("ANONYMOUS_MODE", "true").lower() == "true"
31
  TOOL_SUPPORT: bool = os.getenv("TOOL_SUPPORT", "true").lower() == "true"
32
  SCAN_LIMIT: int = int(os.getenv("SCAN_LIMIT", "200000"))
33
  SKIP_AUTH_TOKEN: bool = os.getenv("SKIP_AUTH_TOKEN", "false").lower() == "true"
34
-
 
 
 
 
35
  # Browser Headers
36
  CLIENT_HEADERS: Dict[str, str] = {
37
  "Content-Type": "application/json",
@@ -44,9 +131,9 @@ class Settings(BaseSettings):
44
  "X-FE-Version": "prod-fe-1.0.70",
45
  "Origin": "https://chat.z.ai",
46
  }
47
-
48
  class Config:
49
  env_file = ".env"
50
 
51
 
52
- settings = Settings()
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
  import os
5
+ from typing import Dict, List, Optional
6
  from pydantic_settings import BaseSettings
7
+ from app.utils.logger import logger
8
 
9
 
10
  class Settings(BaseSettings):
11
  """Application settings"""
12
+
13
  # API Configuration
14
+ API_ENDPOINT: str = "https://chat.z.ai/api/chat/completions"
15
  AUTH_TOKEN: str = os.getenv("AUTH_TOKEN", "sk-your-api-key")
16
+
17
+ # 认证token文件路径
18
+ AUTH_TOKENS_FILE: str = os.getenv("AUTH_TOKENS_FILE", "tokens.txt")
19
+
20
+ # Token池配置
21
+ TOKEN_HEALTH_CHECK_INTERVAL: int = int(os.getenv("TOKEN_HEALTH_CHECK_INTERVAL", "300")) # 5分钟
22
+ TOKEN_FAILURE_THRESHOLD: int = int(os.getenv("TOKEN_FAILURE_THRESHOLD", "3")) # 失败3次后标记为不可用
23
+ TOKEN_RECOVERY_TIMEOUT: int = int(os.getenv("TOKEN_RECOVERY_TIMEOUT", "1800")) # 30分钟后重试失败的token
24
+
25
+ def _load_tokens_from_file(self, file_path: str) -> List[str]:
26
+ """
27
+ 从文件加载token列表
28
+
29
+ 支持多种格式的混合使用:
30
+ 1. 每行一个token(换行分隔)
31
+ 2. 逗号分隔的token
32
+ 3. 混合格式(同时支持换行和逗号分隔)
33
+ """
34
+ tokens = []
35
+ try:
36
+ if os.path.exists(file_path):
37
+ with open(file_path, 'r', encoding='utf-8') as f:
38
+ content = f.read().strip()
39
+
40
+ if not content:
41
+ logger.debug(f"📄 Token文件为空: {file_path}")
42
+ return tokens
43
+
44
+ logger.debug(f"📄 开始解析token文件: {file_path}")
45
+
46
+ # 智能解析:同时支持换行和逗号分隔
47
+ # 1. 先按换行符分割处理每一行
48
+ lines = content.split('\n')
49
+
50
+ for line in lines:
51
+ line = line.strip()
52
+ # 跳过空行和注释行
53
+ if not line or line.startswith('#'):
54
+ continue
55
+
56
+ # 2. 检查当前行是否包含逗号分隔
57
+ if ',' in line:
58
+ # 按逗号分割当前行
59
+ comma_tokens = line.split(',')
60
+ for token in comma_tokens:
61
+ token = token.strip()
62
+ if token: # 跳过空token
63
+ tokens.append(token)
64
+ else:
65
+ # 整行作为一个token
66
+ tokens.append(line)
67
+
68
+ logger.info(f"📄 从文件加载了 {len(tokens)} 个token: {file_path}")
69
+ else:
70
+ logger.debug(f"📄 Token文件不存在: {file_path}")
71
+ except Exception as e:
72
+ logger.error(f"❌ 读取token文件失败 {file_path}: {e}")
73
+ return tokens
74
+
75
+ @property
76
+ def auth_token_list(self) -> List[str]:
77
+ """
78
+ 解析认证token列表
79
+
80
+ 仅从AUTH_TOKENS_FILE指定的文件加载token
81
+ """
82
+ # 从文件加载token
83
+ tokens = self._load_tokens_from_file(self.AUTH_TOKENS_FILE)
84
+
85
+ # 去重,保持顺序
86
+ if tokens:
87
+ seen = set()
88
+ unique_tokens = []
89
+ for token in tokens:
90
+ if token not in seen:
91
+ unique_tokens.append(token)
92
+ seen.add(token)
93
+
94
+ # 记录去重信息
95
+ duplicate_count = len(tokens) - len(unique_tokens)
96
+ if duplicate_count > 0:
97
+ logger.warning(f"⚠️ 检测到 {duplicate_count} 个重复token,已自动去重")
98
+
99
+ return unique_tokens
100
+
101
+ return []
102
+
103
  # Model Configuration
104
  PRIMARY_MODEL: str = os.getenv("PRIMARY_MODEL", "GLM-4.5")
105
  THINKING_MODEL: str = os.getenv("THINKING_MODEL", "GLM-4.5-Thinking")
106
  SEARCH_MODEL: str = os.getenv("SEARCH_MODEL", "GLM-4.5-Search")
107
  AIR_MODEL: str = os.getenv("AIR_MODEL", "GLM-4.5-Air")
108
+
109
  # Server Configuration
110
  LISTEN_PORT: int = int(os.getenv("LISTEN_PORT", "8080"))
111
  DEBUG_LOGGING: bool = os.getenv("DEBUG_LOGGING", "true").lower() == "true"
112
+
 
 
113
  ANONYMOUS_MODE: bool = os.getenv("ANONYMOUS_MODE", "true").lower() == "true"
114
  TOOL_SUPPORT: bool = os.getenv("TOOL_SUPPORT", "true").lower() == "true"
115
  SCAN_LIMIT: int = int(os.getenv("SCAN_LIMIT", "200000"))
116
  SKIP_AUTH_TOKEN: bool = os.getenv("SKIP_AUTH_TOKEN", "false").lower() == "true"
117
+
118
+ # Retry Configuration
119
+ MAX_RETRIES: int = int(os.getenv("MAX_RETRIES", "5"))
120
+ RETRY_DELAY: float = float(os.getenv("RETRY_DELAY", "1.0")) # 初始重试延迟(秒)
121
+
122
  # Browser Headers
123
  CLIENT_HEADERS: Dict[str, str] = {
124
  "Content-Type": "application/json",
 
131
  "X-FE-Version": "prod-fe-1.0.70",
132
  "Origin": "https://chat.z.ai",
133
  }
134
+
135
  class Config:
136
  env_file = ".env"
137
 
138
 
139
+ settings = Settings()
app/core/openai.py CHANGED
@@ -1,24 +1,29 @@
1
- """
2
- OpenAI API endpoints
3
- """
4
 
5
  import time
 
 
6
  from datetime import datetime
7
- from typing import List
8
  from fastapi import APIRouter, Header, HTTPException
9
  from fastapi.responses import StreamingResponse
 
10
 
11
  from app.core.config import settings
12
- from app.models.schemas import (
13
- OpenAIRequest, Message, UpstreamRequest, ModelItem,
14
- ModelsResponse, Model
15
- )
16
- from app.utils.helpers import debug_log, generate_request_ids, get_auth_token
17
- from app.utils.tools import process_messages_with_tools, content_to_string
18
- from app.core.response_handlers import StreamResponseHandler, NonStreamResponseHandler
19
 
20
  router = APIRouter()
21
 
 
 
 
22
 
23
  @router.get("/v1/models")
24
  async def list_models():
@@ -26,150 +31,555 @@ async def list_models():
26
  current_time = int(time.time())
27
  response = ModelsResponse(
28
  data=[
29
- Model(
30
- id=settings.PRIMARY_MODEL,
31
- created=current_time,
32
- owned_by="z.ai"
33
- ),
34
- Model(
35
- id=settings.THINKING_MODEL,
36
- created=current_time,
37
- owned_by="z.ai"
38
- ),
39
- Model(
40
- id=settings.SEARCH_MODEL,
41
- created=current_time,
42
- owned_by="z.ai"
43
- ),
44
- Model(
45
- id=settings.AIR_MODEL,
46
- created=current_time,
47
- owned_by="z.ai"
48
- ),
49
  ]
50
  )
51
  return response
52
 
53
 
54
  @router.post("/v1/chat/completions")
55
- async def chat_completions(
56
- request: OpenAIRequest,
57
- authorization: str = Header(...)
58
- ):
59
- """Handle chat completion requests"""
60
- debug_log("收到chat completions请求")
61
-
62
  try:
63
  # Validate API key (skip if SKIP_AUTH_TOKEN is enabled)
64
  if not settings.SKIP_AUTH_TOKEN:
65
  if not authorization.startswith("Bearer "):
66
- debug_log("缺少或无效的Authorization头")
67
  raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
68
-
69
  api_key = authorization[7:]
70
  if api_key != settings.AUTH_TOKEN:
71
- debug_log(f"无效的API key: {api_key}")
72
  raise HTTPException(status_code=401, detail="Invalid API key")
73
-
74
- debug_log(f"API key验证通过,AUTH_TOKEN={api_key[:8]}......")
75
- else:
76
- debug_log("SKIP_AUTH_TOKEN已启用,跳过API key验证")
77
- debug_log(f"请求解析成功 - 模型: {request.model}, 流式: {request.stream}, 消息数: {len(request.messages)}")
78
-
79
- # Generate IDs
80
- chat_id, msg_id = generate_request_ids()
81
-
82
- # Process messages with tools
83
- processed_messages = process_messages_with_tools(
84
- [m.model_dump() for m in request.messages],
85
- request.tools,
86
- request.tool_choice
87
- )
88
-
89
- # Convert back to Message objects
90
- upstream_messages: List[Message] = []
91
- for msg in processed_messages:
92
- content = content_to_string(msg.get("content"))
93
-
94
- upstream_messages.append(Message(
95
- role=msg["role"],
96
- content=content,
97
- reasoning_content=msg.get("reasoning_content")
98
- ))
99
 
100
- # Determine model features
101
- is_thinking = request.model == settings.THINKING_MODEL
102
- is_search = request.model == settings.SEARCH_MODEL
103
- is_air = request.model == settings.AIR_MODEL
104
- search_mcp = "deep-web-search" if is_search else ""
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
105
 
106
- # Determine upstream model ID based on requested model
107
- if is_air:
108
- upstream_model_id = "0727-106B-API" # AIR model upstream ID
109
- upstream_model_name = "GLM-4.5-Air"
110
- else:
111
- upstream_model_id = "0727-360B-API" # Default upstream model ID
112
- upstream_model_name = "GLM-4.5"
 
 
 
 
 
 
113
 
114
- # Build upstream request
115
- upstream_req = UpstreamRequest(
116
- stream=True, # Always use streaming from upstream
117
- chat_id=chat_id,
118
- id=msg_id,
119
- model=upstream_model_id, # Dynamic upstream model ID
120
- messages=upstream_messages,
121
- params={},
122
- features={
123
- "enable_thinking": is_thinking,
124
- "web_search": is_search,
125
- "auto_web_search": is_search,
126
- },
127
- background_tasks={
128
- "title_generation": False,
129
- "tags_generation": False,
130
  },
131
- mcp_servers=[search_mcp] if search_mcp else [],
132
- model_item=ModelItem(
133
- id=upstream_model_id,
134
- name=upstream_model_name,
135
- owned_by="openai"
136
- ),
137
- tool_servers=[],
138
- variables={
139
- "{{USER_NAME}}": "User",
140
- "{{USER_LOCATION}}": "Unknown",
141
- "{{CURRENT_DATETIME}}": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
142
- }
143
  )
144
-
145
- # Get authentication token
146
- auth_token = get_auth_token()
147
-
148
- # Check if tools are enabled and present
149
- has_tools = (settings.TOOL_SUPPORT and
150
- request.tools and
151
- len(request.tools) > 0 and
152
- request.tool_choice != "none")
153
-
154
- # Handle response based on stream flag
155
- if request.stream:
156
- handler = StreamResponseHandler(upstream_req, chat_id, auth_token, has_tools)
157
- return StreamingResponse(
158
- handler.handle(),
159
- media_type="text/event-stream",
160
- headers={
161
- "Cache-Control": "no-cache",
162
- "Connection": "keep-alive",
163
- }
164
- )
165
- else:
166
- handler = NonStreamResponseHandler(upstream_req, chat_id, auth_token, has_tools)
167
- return handler.handle()
168
-
169
  except HTTPException:
170
  raise
171
  except Exception as e:
172
- debug_log(f"处理请求时发生错误: {str(e)}")
173
  import traceback
174
- debug_log(f"错误堆栈: {traceback.format_exc()}")
175
- raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
  import time
5
+ import json
6
+ import asyncio
7
  from datetime import datetime
8
+ from typing import List, Dict, Any
9
  from fastapi import APIRouter, Header, HTTPException
10
  from fastapi.responses import StreamingResponse
11
+ import httpx
12
 
13
  from app.core.config import settings
14
+ from app.models.schemas import OpenAIRequest, Message, ModelsResponse, Model
15
+ from app.utils.logger import get_logger
16
+ from app.core.zai_transformer import ZAITransformer, generate_uuid
17
+ from app.utils.sse_tool_handler import SSEToolHandler
18
+ from app.utils.token_pool import get_token_pool
19
+
20
+ logger = get_logger()
21
 
22
  router = APIRouter()
23
 
24
+ # 全局转换器实例
25
+ transformer = ZAITransformer()
26
+
27
 
28
  @router.get("/v1/models")
29
  async def list_models():
 
31
  current_time = int(time.time())
32
  response = ModelsResponse(
33
  data=[
34
+ Model(id=settings.PRIMARY_MODEL, created=current_time, owned_by="z.ai"),
35
+ Model(id=settings.THINKING_MODEL, created=current_time, owned_by="z.ai"),
36
+ Model(id=settings.SEARCH_MODEL, created=current_time, owned_by="z.ai"),
37
+ Model(id=settings.AIR_MODEL, created=current_time, owned_by="z.ai"),
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
38
  ]
39
  )
40
  return response
41
 
42
 
43
  @router.post("/v1/chat/completions")
44
+ async def chat_completions(request: OpenAIRequest, authorization: str = Header(...)):
45
+ """Handle chat completion requests with ZAI transformer"""
46
+ role = request.messages[0].role if request.messages else "unknown"
47
+ logger.info(f"😶‍🌫️ 收到 客户端 请求 - 模型: {request.model}, 流式: {request.stream}, 消息数: {len(request.messages)}, 角色: {role}, 工具数: {len(request.tools) if request.tools else 0}")
48
+
 
 
49
  try:
50
  # Validate API key (skip if SKIP_AUTH_TOKEN is enabled)
51
  if not settings.SKIP_AUTH_TOKEN:
52
  if not authorization.startswith("Bearer "):
 
53
  raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
54
+
55
  api_key = authorization[7:]
56
  if api_key != settings.AUTH_TOKEN:
 
57
  raise HTTPException(status_code=401, detail="Invalid API key")
58
+
59
+ # 使用新的转换器转换请求
60
+ request_dict = request.model_dump()
61
+ logger.info("🔄 开始转换请求格式: OpenAI -> Z.AI")
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
62
 
63
+ transformed = await transformer.transform_request_in(request_dict)
64
+ # logger.debug(f"🔄 转换后 Z.AI 请求体: {json.dumps(transformed['body'], ensure_ascii=False, indent=2)}")
65
+
66
+ # 调用上游API
67
+ async def stream_response():
68
+ """流式响应生成器(包含重试机制)"""
69
+ retry_count = 0
70
+ last_error = None
71
+ current_token = transformed.get("token", "") # 获取当前使用的token
72
+
73
+ while retry_count <= settings.MAX_RETRIES:
74
+ try:
75
+ # 如果是重试,重新获取令牌并更新请求
76
+ if retry_count > 0:
77
+ delay = settings.RETRY_DELAY
78
+ logger.warning(f"重试请求 ({retry_count}/{settings.MAX_RETRIES}) - 等待 {delay:.1f}s")
79
+ await asyncio.sleep(delay)
80
+
81
+ # 标记前一个token失败(如果不是匿名模式)
82
+ if current_token and not settings.ANONYMOUS_MODE:
83
+ transformer.mark_token_failure(current_token, Exception(f"Retry {retry_count}: {last_error}"))
84
+
85
+ # 重新获取令牌
86
+ logger.info("🔑 重新获取令牌用于重试...")
87
+ new_token = await transformer.get_token()
88
+ if not new_token:
89
+ logger.error("❌ 重试时无法获取有效的认证令牌")
90
+ raise Exception("重试时无法获取有效的认证令牌")
91
+ transformed["config"]["headers"]["Authorization"] = f"Bearer {new_token}"
92
+ current_token = new_token
93
+
94
+ async with httpx.AsyncClient(timeout=60.0) as client:
95
+ # 发送请求到上游
96
+ logger.info(f"🎯 发送请求到 Z.AI: {transformed['config']['url']}")
97
+ async with client.stream(
98
+ "POST",
99
+ transformed["config"]["url"],
100
+ json=transformed["body"],
101
+ headers=transformed["config"]["headers"],
102
+ ) as response:
103
+ # 检查响应状态码
104
+ if response.status_code == 400:
105
+ # 400 错误,触发重试
106
+ error_text = await response.aread()
107
+ error_msg = error_text.decode('utf-8', errors='ignore')
108
+ logger.warning(f"❌ 上游返回 400 错误 (尝试 {retry_count + 1}/{settings.MAX_RETRIES + 1})")
109
+
110
+ retry_count += 1
111
+ last_error = f"400 Bad Request: {error_msg}"
112
+
113
+ # 如果还有重试机会,继续循环
114
+ if retry_count <= settings.MAX_RETRIES:
115
+ continue
116
+ else:
117
+ # 达到最大重试次数,抛出错误
118
+ logger.error(f"❌ 达到最大重试次数 ({settings.MAX_RETRIES}),请求失败")
119
+ error_response = {
120
+ "error": {
121
+ "message": f"Request failed after {settings.MAX_RETRIES} retries: {last_error}",
122
+ "type": "upstream_error",
123
+ "code": 400
124
+ }
125
+ }
126
+ yield f"data: {json.dumps(error_response)}\n\n"
127
+ yield "data: [DONE]\n\n"
128
+ return
129
+
130
+ elif response.status_code != 200:
131
+ # 其他错误,直接返回
132
+ logger.error(f"❌ 上游返回错误: {response.status_code}")
133
+ error_text = await response.aread()
134
+ error_msg = error_text.decode('utf-8', errors='ignore')
135
+ logger.error(f"❌ 错误详情: {error_msg}")
136
+
137
+ error_response = {
138
+ "error": {
139
+ "message": f"Upstream error: {response.status_code}",
140
+ "type": "upstream_error",
141
+ "code": response.status_code
142
+ }
143
+ }
144
+ yield f"data: {json.dumps(error_response)}\n\n"
145
+ yield "data: [DONE]\n\n"
146
+ return
147
+
148
+ # 200 成功,处理响应
149
+ logger.info(f"✅ Z.AI 响应成功,开始处理 SSE 流")
150
+ if retry_count > 0:
151
+ logger.info(f"✨ 第 {retry_count} 次重试成功")
152
+
153
+ # 标记token使用成功(如果不是匿名模式)
154
+ if current_token and not settings.ANONYMOUS_MODE:
155
+ transformer.mark_token_success(current_token)
156
+
157
+ # 初始化工具处理器(如果需要)
158
+ has_tools = transformed["body"].get("tools") is not None
159
+ tool_handler = None
160
+ if has_tools:
161
+ chat_id = transformed["body"]["chat_id"]
162
+ model = request.model
163
+ tool_handler = SSEToolHandler(chat_id, model)
164
+ logger.info(f"🔧 初始化工具处理器: {len(transformed['body'].get('tools', []))} 个工具")
165
+
166
+ # 处理状态
167
+ has_thinking = False
168
+ thinking_signature = None
169
+
170
+ # 处理SSE流
171
+ buffer = ""
172
+ line_count = 0
173
+ logger.debug("📡 开始接收 SSE 流数据...")
174
+
175
+ async for line in response.aiter_lines():
176
+ line_count += 1
177
+ if not line:
178
+ continue
179
+
180
+ # 累积到buffer处理完整的数据行
181
+ buffer += line + "\n"
182
+
183
+ # 检查是否有完整的data行
184
+ while "\n" in buffer:
185
+ current_line, buffer = buffer.split("\n", 1)
186
+ if not current_line.strip():
187
+ continue
188
+
189
+ if current_line.startswith("data:"):
190
+ chunk_str = current_line[5:].strip()
191
+ if not chunk_str or chunk_str == "[DONE]":
192
+ if chunk_str == "[DONE]":
193
+ yield "data: [DONE]\n\n"
194
+ continue
195
+
196
+ logger.debug(f"📦 解析数据块: {chunk_str[:1000]}..." if len(chunk_str) > 1000 else f"📦 解析数据块: {chunk_str}")
197
+
198
+ try:
199
+ chunk = json.loads(chunk_str)
200
+
201
+ if chunk.get("type") == "chat:completion":
202
+ data = chunk.get("data", {})
203
+ phase = data.get("phase")
204
+
205
+ # 记录每个阶段(只在阶段变化时记录)
206
+ if phase and phase != getattr(stream_response, '_last_phase', None):
207
+ logger.info(f"📈 SSE 阶段: {phase}")
208
+ stream_response._last_phase = phase
209
+
210
+ # 处理工具调用
211
+ if phase == "tool_call" and tool_handler:
212
+ for output in tool_handler.process_tool_call_phase(data, True):
213
+ yield output
214
+
215
+ # 处理其他阶段(工具结束)
216
+ elif phase == "other" and tool_handler:
217
+ for output in tool_handler.process_other_phase(data, True):
218
+ yield output
219
+
220
+ # 处理思考内容
221
+ elif phase == "thinking":
222
+ if not has_thinking:
223
+ has_thinking = True
224
+ has_thinking = True
225
+ # 发送初始角色
226
+ role_chunk = {
227
+ "choices": [
228
+ {
229
+ "delta": {"role": "assistant"},
230
+ "finish_reason": None,
231
+ "index": 0,
232
+ "logprobs": None,
233
+ }
234
+ ],
235
+ "created": int(time.time()),
236
+ "id": transformed["body"]["chat_id"],
237
+ "model": request.model,
238
+ "object": "chat.completion.chunk",
239
+ "system_fingerprint": "fp_zai_001",
240
+ }
241
+ yield f"data: {json.dumps(role_chunk)}\n\n"
242
+
243
+ delta_content = data.get("delta_content", "")
244
+ if delta_content:
245
+ # 处理思考内容格式
246
+ if delta_content.startswith("<details"):
247
+ content = (
248
+ delta_content.split("</summary>\n>")[-1].strip()
249
+ if "</summary>\n>" in delta_content
250
+ else delta_content
251
+ )
252
+ else:
253
+ content = delta_content
254
+
255
+ thinking_chunk = {
256
+ "choices": [
257
+ {
258
+ "delta": {
259
+ "role": "assistant",
260
+ "thinking": {"content": content},
261
+ },
262
+ "finish_reason": None,
263
+ "index": 0,
264
+ "logprobs": None,
265
+ }
266
+ ],
267
+ "created": int(time.time()),
268
+ "id": transformed["body"]["chat_id"],
269
+ "model": request.model,
270
+ "object": "chat.completion.chunk",
271
+ "system_fingerprint": "fp_zai_001",
272
+ }
273
+ yield f"data: {json.dumps(thinking_chunk)}\n\n"
274
+
275
+ # 处理答案内容
276
+ elif phase == "answer":
277
+ edit_content = data.get("edit_content", "")
278
+ delta_content = data.get("delta_content", "")
279
+
280
+ # 处理思考结束和答案开始
281
+ if edit_content and "</details>\n" in edit_content:
282
+ if has_thinking:
283
+ # 发送思考签名
284
+ thinking_signature = str(int(time.time() * 1000))
285
+ sig_chunk = {
286
+ "choices": [
287
+ {
288
+ "delta": {
289
+ "role": "assistant",
290
+ "thinking": {
291
+ "content": "",
292
+ "signature": thinking_signature,
293
+ },
294
+ },
295
+ "finish_reason": None,
296
+ "index": 0,
297
+ "logprobs": None,
298
+ }
299
+ ],
300
+ "created": int(time.time()),
301
+ "id": transformed["body"]["chat_id"],
302
+ "model": request.model,
303
+ "object": "chat.completion.chunk",
304
+ "system_fingerprint": "fp_zai_001",
305
+ }
306
+ yield f"data: {json.dumps(sig_chunk)}\n\n"
307
+
308
+ # 提取答案内容
309
+ content_after = edit_content.split("</details>\n")[-1]
310
+ if content_after:
311
+ content_chunk = {
312
+ "choices": [
313
+ {
314
+ "delta": {
315
+ "role": "assistant",
316
+ "content": content_after,
317
+ },
318
+ "finish_reason": None,
319
+ "index": 0,
320
+ "logprobs": None,
321
+ }
322
+ ],
323
+ "created": int(time.time()),
324
+ "id": transformed["body"]["chat_id"],
325
+ "model": request.model,
326
+ "object": "chat.completion.chunk",
327
+ "system_fingerprint": "fp_zai_001",
328
+ }
329
+ yield f"data: {json.dumps(content_chunk)}\n\n"
330
+
331
+ # 处理增量内容
332
+ elif delta_content:
333
+ # 如果还没有发送角色
334
+ if not has_thinking:
335
+ role_chunk = {
336
+ "choices": [
337
+ {
338
+ "delta": {"role": "assistant"},
339
+ "finish_reason": None,
340
+ "index": 0,
341
+ "logprobs": None,
342
+ }
343
+ ],
344
+ "created": int(time.time()),
345
+ "id": transformed["body"]["chat_id"],
346
+ "model": request.model,
347
+ "object": "chat.completion.chunk",
348
+ "system_fingerprint": "fp_zai_001",
349
+ }
350
+ yield f"data: {json.dumps(role_chunk)}\n\n"
351
+
352
+ content_chunk = {
353
+ "choices": [
354
+ {
355
+ "delta": {
356
+ "role": "assistant",
357
+ "content": delta_content,
358
+ },
359
+ "finish_reason": None,
360
+ "index": 0,
361
+ "logprobs": None,
362
+ }
363
+ ],
364
+ "created": int(time.time()),
365
+ "id": transformed["body"]["chat_id"],
366
+ "model": request.model,
367
+ "object": "chat.completion.chunk",
368
+ "system_fingerprint": "fp_zai_001",
369
+ }
370
+ output_data = f"data: {json.dumps(content_chunk)}\n\n"
371
+ logger.debug(f"➡️ 输出内容块到客户端: {output_data[:1000]}...")
372
+ yield output_data
373
+
374
+ # 处理完成
375
+ if data.get("usage"):
376
+ logger.info(f"📦 完成响应 - 使用统计: {json.dumps(data['usage'])}")
377
+
378
+ # 只有在非工具调用模式下才发送普通完成信号
379
+ if not tool_handler or not tool_handler.has_tool_call:
380
+ finish_chunk = {
381
+ "choices": [
382
+ {
383
+ "delta": {"role": "assistant", "content": ""},
384
+ "finish_reason": "stop",
385
+ "index": 0,
386
+ "logprobs": None,
387
+ }
388
+ ],
389
+ "usage": data["usage"],
390
+ "created": int(time.time()),
391
+ "id": transformed["body"]["chat_id"],
392
+ "model": request.model,
393
+ "object": "chat.completion.chunk",
394
+ "system_fingerprint": "fp_zai_001",
395
+ }
396
+ finish_output = f"data: {json.dumps(finish_chunk)}\n\n"
397
+ logger.debug(f"➡️ 发送完成信号: {finish_output[:1000]}...")
398
+ yield finish_output
399
+ logger.debug("➡️ 发送 [DONE]")
400
+ yield "data: [DONE]\n\n"
401
+
402
+ except json.JSONDecodeError as e:
403
+ logger.debug(f"❌ JSON解析错误: {e}, 内容: {chunk_str[:1000]}")
404
+ except Exception as e:
405
+ logger.error(f"❌ 处理chunk错误: {e}")
406
+
407
+ # 确保发送结束信号
408
+ if not tool_handler or not tool_handler.has_tool_call:
409
+ logger.debug("📤 发送最终 [DONE] 信号")
410
+ yield "data: [DONE]\n\n"
411
+
412
+ logger.info(f"✅ SSE 流处理完成,共处理 {line_count} 行数据")
413
+ # 成功处理完成,退出重试循环
414
+ return
415
+
416
+ except Exception as e:
417
+ logger.error(f"❌ 流处理错误: {e}")
418
+ import traceback
419
+ logger.error(traceback.format_exc())
420
+
421
+ # 标记token失败(如果不是匿名模式)
422
+ if current_token and not settings.ANONYMOUS_MODE:
423
+ transformer.mark_token_failure(current_token, e)
424
+
425
+ # 检查是否还可以重试
426
+ retry_count += 1
427
+ last_error = str(e)
428
+
429
+ if retry_count > settings.MAX_RETRIES:
430
+ # 达到最大重试次数,返回错误
431
+ logger.error(f"❌ 达到最大重试次数 ({settings.MAX_RETRIES}),流处理失败")
432
+ error_response = {
433
+ "error": {
434
+ "message": f"Stream processing failed after {settings.MAX_RETRIES} retries: {last_error}",
435
+ "type": "stream_error"
436
+ }
437
+ }
438
+ yield f"data: {json.dumps(error_response)}\n\n"
439
+ yield "data: [DONE]\n\n"
440
+ return
441
+
442
+ # 返回流式响应
443
+ logger.info("🚀 启动 SSE 流式响应")
444
 
445
+ # 创建一个包装的生成器来追踪数据流
446
+ async def logged_stream():
447
+ chunk_count = 0
448
+ try:
449
+ logger.debug("📤 开始向客户端流式传输数据...")
450
+ async for chunk in stream_response():
451
+ chunk_count += 1
452
+ logger.debug(f"📤 发送块[{chunk_count}]: {chunk[:1000]}..." if len(chunk) > 1000 else f" 📤 发送块[{chunk_count}]: {chunk}")
453
+ yield chunk
454
+ logger.info(f"✅ 流式传输完成,共发送 {chunk_count} 个数据块")
455
+ except Exception as e:
456
+ logger.error(f"❌ 流式传输中断: {e}")
457
+ raise
458
 
459
+ return StreamingResponse(
460
+ logged_stream(),
461
+ media_type="text/event-stream",
462
+ headers={
463
+ "Cache-Control": "no-cache",
464
+ "Connection": "keep-alive",
 
 
 
 
 
 
 
 
 
 
465
  },
 
 
 
 
 
 
 
 
 
 
 
 
466
  )
467
+
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
468
  except HTTPException:
469
  raise
470
  except Exception as e:
471
+ logger.error(f"处理请求时发生错误: {str(e)}")
472
  import traceback
473
+
474
+ logger.error(f" 错误堆栈: {traceback.format_exc()}")
475
+ raise HTTPException(status_code=500, detail=f"Internal server error: {str(e)}")
476
+
477
+
478
+ @router.get("/v1/token-pool/status")
479
+ async def get_token_pool_status():
480
+ """获取token池状态信息"""
481
+ try:
482
+ token_pool = get_token_pool()
483
+ if not token_pool:
484
+ return {
485
+ "status": "disabled",
486
+ "message": "Token池未初始化,当前仅使用匿名模式",
487
+ "anonymous_mode": settings.ANONYMOUS_MODE,
488
+ "auth_tokens_file": settings.AUTH_TOKENS_FILE,
489
+ "auth_tokens_configured": len(settings.auth_token_list) > 0
490
+ }
491
+
492
+ pool_status = token_pool.get_pool_status()
493
+ return {
494
+ "status": "active",
495
+ "pool_info": pool_status,
496
+ "config": {
497
+ "anonymous_mode": settings.ANONYMOUS_MODE,
498
+ "failure_threshold": settings.TOKEN_FAILURE_THRESHOLD,
499
+ "recovery_timeout": settings.TOKEN_RECOVERY_TIMEOUT,
500
+ "health_check_interval": settings.TOKEN_HEALTH_CHECK_INTERVAL
501
+ }
502
+ }
503
+ except Exception as e:
504
+ logger.error(f"获取token池状态失败: {e}")
505
+ raise HTTPException(status_code=500, detail=f"Failed to get token pool status: {str(e)}")
506
+
507
+
508
+ @router.post("/v1/token-pool/health-check")
509
+ async def trigger_health_check():
510
+ """手动触发token池健康检查"""
511
+ try:
512
+ token_pool = get_token_pool()
513
+ if not token_pool:
514
+ raise HTTPException(status_code=404, detail="Token池未初始化")
515
+
516
+ # 记录开始时间
517
+ import time
518
+ start_time = time.time()
519
+
520
+ logger.info("🔍 API触发Token池健康检查...")
521
+ await token_pool.health_check_all()
522
+
523
+ # 计算耗时
524
+ duration = time.time() - start_time
525
+
526
+ pool_status = token_pool.get_pool_status()
527
+
528
+ # 统计健康检查结果 - 基于实际的健康状态
529
+ total_tokens = pool_status['total_tokens']
530
+ healthy_tokens = sum(1 for token_info in pool_status['tokens'] if token_info['is_healthy'])
531
+ unhealthy_tokens = total_tokens - healthy_tokens
532
+
533
+ # 构建响应
534
+ response = {
535
+ "status": "completed",
536
+ "message": f"健康检查已完成,耗时 {duration:.2f} 秒",
537
+ "summary": {
538
+ "total_tokens": total_tokens,
539
+ "healthy_tokens": healthy_tokens,
540
+ "unhealthy_tokens": unhealthy_tokens,
541
+ "health_rate": f"{(healthy_tokens/total_tokens*100):.1f}%" if total_tokens > 0 else "0%",
542
+ "duration_seconds": round(duration, 2)
543
+ },
544
+ "pool_info": pool_status
545
+ }
546
+
547
+ # 添加建议
548
+ if unhealthy_tokens > 0:
549
+ response["recommendations"] = []
550
+ if unhealthy_tokens == total_tokens:
551
+ response["recommendations"].append("所有token都不健康,请检查token配置和网络连接")
552
+ else:
553
+ response["recommendations"].append(f"有 {unhealthy_tokens} 个token不健康,建议检查这些token的有效性")
554
+
555
+ logger.info(f"✅ API健康检查完成: {healthy_tokens}/{total_tokens} 个token健康")
556
+ return response
557
+ except Exception as e:
558
+ logger.error(f"健康检查失败: {e}")
559
+ raise HTTPException(status_code=500, detail=f"Health check failed: {str(e)}")
560
+
561
+
562
+ @router.post("/v1/token-pool/update")
563
+ async def update_token_pool(tokens: List[str]):
564
+ """动态更新token池"""
565
+ try:
566
+ from app.utils.token_pool import update_token_pool
567
+
568
+ # 过滤空token
569
+ valid_tokens = [token.strip() for token in tokens if token.strip()]
570
+ if not valid_tokens:
571
+ raise HTTPException(status_code=400, detail="至少需要提供一个有效的token")
572
+
573
+ update_token_pool(valid_tokens)
574
+
575
+ token_pool = get_token_pool()
576
+ pool_status = token_pool.get_pool_status() if token_pool else None
577
+
578
+ return {
579
+ "status": "updated",
580
+ "message": f"Token池已更新,共 {len(valid_tokens)} 个token",
581
+ "pool_info": pool_status
582
+ }
583
+ except Exception as e:
584
+ logger.error(f"更新token池失败: {e}")
585
+ raise HTTPException(status_code=500, detail=f"Failed to update token pool: {str(e)}")
app/core/response_handlers.py DELETED
@@ -1,333 +0,0 @@
1
- """
2
- Response handlers for streaming and non-streaming responses
3
- """
4
-
5
- import json
6
- import time
7
- from typing import Generator, Optional
8
- import requests
9
- from fastapi import HTTPException
10
- from fastapi.responses import JSONResponse, StreamingResponse
11
-
12
- from app.core.config import settings
13
- from app.models.schemas import (
14
- Message, Delta, Choice, Usage, OpenAIResponse,
15
- UpstreamRequest, UpstreamData, UpstreamError, ModelItem
16
- )
17
- from app.utils.helpers import debug_log, call_upstream_api, transform_thinking_content
18
- from app.utils.sse_parser import SSEParser
19
- from app.utils.tools import extract_tool_invocations, remove_tool_json_content
20
-
21
-
22
- def create_openai_response_chunk(
23
- model: str,
24
- delta: Optional[Delta] = None,
25
- finish_reason: Optional[str] = None
26
- ) -> OpenAIResponse:
27
- """Create OpenAI response chunk for streaming"""
28
- return OpenAIResponse(
29
- id=f"chatcmpl-{int(time.time())}",
30
- object="chat.completion.chunk",
31
- created=int(time.time()),
32
- model=model,
33
- choices=[Choice(
34
- index=0,
35
- delta=delta or Delta(),
36
- finish_reason=finish_reason
37
- )]
38
- )
39
-
40
-
41
- def handle_upstream_error(error: UpstreamError) -> Generator[str, None, None]:
42
- """Handle upstream error response"""
43
- debug_log(f"上游错误: code={error.code}, detail={error.detail}")
44
-
45
- # Send end chunk
46
- end_chunk = create_openai_response_chunk(
47
- model=settings.PRIMARY_MODEL,
48
- finish_reason="stop"
49
- )
50
- yield f"data: {end_chunk.model_dump_json()}\n\n"
51
- yield "data: [DONE]\n\n"
52
-
53
-
54
- class ResponseHandler:
55
- """Base class for response handling"""
56
-
57
- def __init__(self, upstream_req: UpstreamRequest, chat_id: str, auth_token: str):
58
- self.upstream_req = upstream_req
59
- self.chat_id = chat_id
60
- self.auth_token = auth_token
61
-
62
- def _call_upstream(self) -> requests.Response:
63
- """Call upstream API with error handling"""
64
- try:
65
- return call_upstream_api(self.upstream_req, self.chat_id, self.auth_token)
66
- except Exception as e:
67
- debug_log(f"调用上游失败: {e}")
68
- raise
69
-
70
- def _handle_upstream_error(self, response: requests.Response) -> None:
71
- """Handle upstream error response"""
72
- debug_log(f"上游返回错误状态: {response.status_code}")
73
- if settings.DEBUG_LOGGING:
74
- debug_log(f"上游错误响应: {response.text}")
75
-
76
-
77
- class StreamResponseHandler(ResponseHandler):
78
- """Handler for streaming responses"""
79
-
80
- def __init__(self, upstream_req: UpstreamRequest, chat_id: str, auth_token: str, has_tools: bool = False):
81
- super().__init__(upstream_req, chat_id, auth_token)
82
- self.has_tools = has_tools
83
- self.buffered_content = ""
84
- self.tool_calls = None
85
-
86
- def handle(self) -> Generator[str, None, None]:
87
- """Handle streaming response"""
88
- debug_log(f"开始处理流式响应 (chat_id={self.chat_id})")
89
-
90
- try:
91
- response = self._call_upstream()
92
- except Exception:
93
- yield "data: {\"error\": \"Failed to call upstream\"}\n\n"
94
- return
95
-
96
- if response.status_code != 200:
97
- self._handle_upstream_error(response)
98
- yield "data: {\"error\": \"Upstream error\"}\n\n"
99
- return
100
-
101
- # Send initial role chunk
102
- first_chunk = create_openai_response_chunk(
103
- model=settings.PRIMARY_MODEL,
104
- delta=Delta(role="assistant")
105
- )
106
- yield f"data: {first_chunk.model_dump_json()}\n\n"
107
-
108
- # Process stream
109
- debug_log("开始读取上游SSE流")
110
- sent_initial_answer = False
111
-
112
- with SSEParser(response, debug_mode=settings.DEBUG_LOGGING) as parser:
113
- for event in parser.iter_json_data(UpstreamData):
114
- upstream_data = event['data']
115
-
116
- # Check for errors
117
- if self._has_error(upstream_data):
118
- error = self._get_error(upstream_data)
119
- yield from handle_upstream_error(error)
120
- break
121
-
122
- debug_log(f"解析成功 - 类型: {upstream_data.type}, 阶段: {upstream_data.data.phase}, "
123
- f"内容长度: {len(upstream_data.data.delta_content)}, 完成: {upstream_data.data.done}")
124
-
125
- # Process content
126
- yield from self._process_content(upstream_data, sent_initial_answer)
127
-
128
- # Check if done
129
- if upstream_data.data.done or upstream_data.data.phase == "done":
130
- debug_log("检测到流结束信号")
131
- yield from self._send_end_chunk()
132
- break
133
-
134
- def _has_error(self, upstream_data: UpstreamData) -> bool:
135
- """Check if upstream data contains error"""
136
- return bool(
137
- upstream_data.error or
138
- upstream_data.data.error or
139
- (upstream_data.data.inner and upstream_data.data.inner.error)
140
- )
141
-
142
- def _get_error(self, upstream_data: UpstreamData) -> UpstreamError:
143
- """Get error from upstream data"""
144
- return (
145
- upstream_data.error or
146
- upstream_data.data.error or
147
- (upstream_data.data.inner.error if upstream_data.data.inner else None)
148
- )
149
-
150
- def _process_content(
151
- self,
152
- upstream_data: UpstreamData,
153
- sent_initial_answer: bool
154
- ) -> Generator[str, None, None]:
155
- """Process content from upstream data"""
156
- content = upstream_data.data.delta_content or upstream_data.data.edit_content
157
-
158
- if not content:
159
- return
160
-
161
- # Transform thinking content
162
- if upstream_data.data.phase == "thinking":
163
- content = transform_thinking_content(content)
164
-
165
- # Buffer content if tools are enabled
166
- if self.has_tools:
167
- self.buffered_content += content
168
- else:
169
- # Handle initial answer content
170
- if (not sent_initial_answer and
171
- upstream_data.data.edit_content and
172
- upstream_data.data.phase == "answer"):
173
-
174
- content = self._extract_edit_content(upstream_data.data.edit_content)
175
- if content:
176
- debug_log(f"发送普通内容: {content}")
177
- chunk = create_openai_response_chunk(
178
- model=settings.PRIMARY_MODEL,
179
- delta=Delta(content=content)
180
- )
181
- yield f"data: {chunk.model_dump_json()}\n\n"
182
- sent_initial_answer = True
183
-
184
- # Handle delta content
185
- if upstream_data.data.delta_content:
186
- if content:
187
- if upstream_data.data.phase == "thinking":
188
- debug_log(f"发送思考内容: {content}")
189
- chunk = create_openai_response_chunk(
190
- model=settings.PRIMARY_MODEL,
191
- delta=Delta(reasoning_content=content)
192
- )
193
- else:
194
- debug_log(f"发送普通内容: {content}")
195
- chunk = create_openai_response_chunk(
196
- model=settings.PRIMARY_MODEL,
197
- delta=Delta(content=content)
198
- )
199
- yield f"data: {chunk.model_dump_json()}\n\n"
200
-
201
- def _extract_edit_content(self, edit_content: str) -> str:
202
- """Extract content from edit_content field"""
203
- parts = edit_content.split("</details>")
204
- return parts[1] if len(parts) > 1 else ""
205
-
206
- def _send_end_chunk(self) -> Generator[str, None, None]:
207
- """Send end chunk and DONE signal"""
208
- finish_reason = "stop"
209
-
210
- if self.has_tools:
211
- # Try to extract tool calls from buffered content
212
- self.tool_calls = extract_tool_invocations(self.buffered_content)
213
-
214
- if self.tool_calls:
215
- # Send tool calls with proper format
216
- for i, tc in enumerate(self.tool_calls):
217
- tool_call_delta = {
218
- "index": i,
219
- "id": tc.get("id"),
220
- "type": tc.get("type", "function"),
221
- "function": tc.get("function", {}),
222
- }
223
-
224
- out_chunk = create_openai_response_chunk(
225
- model=settings.PRIMARY_MODEL,
226
- delta=Delta(tool_calls=[tool_call_delta])
227
- )
228
- yield f"data: {out_chunk.model_dump_json()}\n\n"
229
-
230
- finish_reason = "tool_calls"
231
- else:
232
- # Send regular content
233
- trimmed_content = remove_tool_json_content(self.buffered_content)
234
- if trimmed_content:
235
- content_chunk = create_openai_response_chunk(
236
- model=settings.PRIMARY_MODEL,
237
- delta=Delta(content=trimmed_content)
238
- )
239
- yield f"data: {content_chunk.model_dump_json()}\n\n"
240
-
241
- # Send final chunk
242
- end_chunk = create_openai_response_chunk(
243
- model=settings.PRIMARY_MODEL,
244
- finish_reason=finish_reason
245
- )
246
- yield f"data: {end_chunk.model_dump_json()}\n\n"
247
- yield "data: [DONE]\n\n"
248
- debug_log("流式响应完成")
249
-
250
-
251
- class NonStreamResponseHandler(ResponseHandler):
252
- """Handler for non-streaming responses"""
253
-
254
- def __init__(self, upstream_req: UpstreamRequest, chat_id: str, auth_token: str, has_tools: bool = False):
255
- super().__init__(upstream_req, chat_id, auth_token)
256
- self.has_tools = has_tools
257
-
258
- def handle(self) -> JSONResponse:
259
- """Handle non-streaming response"""
260
- debug_log(f"开始处理非流式响应 (chat_id={self.chat_id})")
261
-
262
- try:
263
- response = self._call_upstream()
264
- except Exception as e:
265
- debug_log(f"调用上游失败: {e}")
266
- raise HTTPException(status_code=502, detail="Failed to call upstream")
267
-
268
- if response.status_code != 200:
269
- self._handle_upstream_error(response)
270
- raise HTTPException(status_code=502, detail="Upstream error")
271
-
272
- # Collect full response
273
- full_content = []
274
- debug_log("开始收集完整响应内容")
275
-
276
- with SSEParser(response, debug_mode=settings.DEBUG_LOGGING) as parser:
277
- for event in parser.iter_json_data(UpstreamData):
278
- upstream_data = event['data']
279
-
280
- if upstream_data.data.delta_content:
281
- content = upstream_data.data.delta_content
282
-
283
- if upstream_data.data.phase == "thinking":
284
- content = transform_thinking_content(content)
285
-
286
- if content:
287
- full_content.append(content)
288
-
289
- if upstream_data.data.done or upstream_data.data.phase == "done":
290
- debug_log("检测到完成信号,停止收集")
291
- break
292
-
293
- final_content = "".join(full_content)
294
- debug_log(f"内容收集完成,最终长度: {len(final_content)}")
295
-
296
- # Handle tool calls for non-streaming
297
- tool_calls = None
298
- finish_reason = "stop"
299
- message_content = final_content
300
-
301
- if self.has_tools:
302
- tool_calls = extract_tool_invocations(final_content)
303
- if tool_calls:
304
- # Content must be null when tool_calls are present (OpenAI spec)
305
- message_content = None
306
- finish_reason = "tool_calls"
307
- debug_log(f"提取到工具调用: {json.dumps(tool_calls, ensure_ascii=False)}")
308
- else:
309
- # Remove tool JSON from content
310
- message_content = remove_tool_json_content(final_content)
311
- if not message_content:
312
- message_content = final_content # 保留原内容如果清理后为空
313
-
314
- # Build response
315
- response_data = OpenAIResponse(
316
- id=f"chatcmpl-{int(time.time())}",
317
- object="chat.completion",
318
- created=int(time.time()),
319
- model=settings.PRIMARY_MODEL,
320
- choices=[Choice(
321
- index=0,
322
- message=Message(
323
- role="assistant",
324
- content=message_content,
325
- tool_calls=tool_calls
326
- ),
327
- finish_reason=finish_reason
328
- )],
329
- usage=Usage()
330
- )
331
-
332
- debug_log("非流式响应发送完成")
333
- return JSONResponse(content=response_data.model_dump(exclude_none=True))
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/core/zai_transformer.py ADDED
@@ -0,0 +1,726 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import json
5
+ import time
6
+ import uuid
7
+ import random
8
+ import requests
9
+ from datetime import datetime
10
+ from typing import Dict, List, Any, Optional, Generator, AsyncGenerator
11
+ import httpx
12
+ import asyncio
13
+ from fake_useragent import UserAgent
14
+
15
+ from app.core.config import settings
16
+ from app.utils.logger import get_logger
17
+ from app.utils.token_pool import get_token_pool, initialize_token_pool
18
+
19
+ logger = get_logger()
20
+
21
+ # 全局 UserAgent 实例(单例模式)
22
+ _user_agent_instance = None
23
+
24
+
25
+ def get_user_agent_instance() -> UserAgent:
26
+ """获取或创建 UserAgent 实例(单例模式)"""
27
+ global _user_agent_instance
28
+ if _user_agent_instance is None:
29
+ _user_agent_instance = UserAgent()
30
+ return _user_agent_instance
31
+
32
+
33
+ def get_dynamic_headers(chat_id: str = "") -> Dict[str, str]:
34
+ """生成动态浏览器headers,包含随机User-Agent"""
35
+ ua = get_user_agent_instance()
36
+
37
+ # 随机选择浏览器类型,偏向Chrome和Edge
38
+ browser_choices = ["chrome", "chrome", "chrome", "edge", "edge", "firefox", "safari"]
39
+ browser_type = random.choice(browser_choices)
40
+
41
+ try:
42
+ if browser_type == "chrome":
43
+ user_agent = ua.chrome
44
+ elif browser_type == "edge":
45
+ user_agent = ua.edge
46
+ elif browser_type == "firefox":
47
+ user_agent = ua.firefox
48
+ elif browser_type == "safari":
49
+ user_agent = ua.safari
50
+ else:
51
+ user_agent = ua.random
52
+ except:
53
+ user_agent = ua.random
54
+
55
+ # 提取版本信息
56
+ chrome_version = "139"
57
+ edge_version = "139"
58
+
59
+ if "Chrome/" in user_agent:
60
+ try:
61
+ chrome_version = user_agent.split("Chrome/")[1].split(".")[0]
62
+ except:
63
+ pass
64
+
65
+ if "Edg/" in user_agent:
66
+ try:
67
+ edge_version = user_agent.split("Edg/")[1].split(".")[0]
68
+ sec_ch_ua = f'"Microsoft Edge";v="{edge_version}", "Chromium";v="{chrome_version}", "Not_A Brand";v="24"'
69
+ except:
70
+ sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
71
+ elif "Firefox/" in user_agent:
72
+ sec_ch_ua = None # Firefox不使用sec-ch-ua
73
+ else:
74
+ sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
75
+
76
+ headers = {
77
+ "Content-Type": "application/json",
78
+ "Accept": "application/json, text/event-stream",
79
+ "User-Agent": user_agent,
80
+ "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
81
+ "X-FE-Version": "prod-fe-1.0.79",
82
+ "Origin": "https://chat.z.ai",
83
+ }
84
+
85
+ if sec_ch_ua:
86
+ headers["sec-ch-ua"] = sec_ch_ua
87
+ headers["sec-ch-ua-mobile"] = "?0"
88
+ headers["sec-ch-ua-platform"] = '"Windows"'
89
+
90
+ if chat_id:
91
+ headers["Referer"] = f"https://chat.z.ai/c/{chat_id}"
92
+ else:
93
+ headers["Referer"] = "https://chat.z.ai/"
94
+
95
+ return headers
96
+
97
+
98
+ def generate_uuid() -> str:
99
+ """生成UUID v4"""
100
+ return str(uuid.uuid4())
101
+
102
+
103
+ def get_auth_token_sync() -> str:
104
+ """同步获取认证令牌(用于非异步场景)"""
105
+ if settings.ANONYMOUS_MODE:
106
+ try:
107
+ headers = get_dynamic_headers()
108
+ response = requests.get("https://chat.z.ai/api/v1/auths/", headers=headers, timeout=10)
109
+ if response.status_code == 200:
110
+ data = response.json()
111
+ token = data.get("token", "")
112
+ if token:
113
+ logger.debug(f"获取访客令牌成功: {token[:20]}...")
114
+ return token
115
+ except Exception as e:
116
+ logger.warning(f"获取访客令牌失败: {e}")
117
+
118
+ # 使用token池获取备份令牌
119
+ token_pool = get_token_pool()
120
+ if token_pool:
121
+ token = token_pool.get_next_token()
122
+ if token:
123
+ logger.debug(f"从token池获取令牌: {token[:20]}...")
124
+ return token
125
+
126
+ # 没有可用的token
127
+ logger.warning("⚠️ 没有可用的备份token")
128
+ return ""
129
+
130
+
131
+ class ZAITransformer:
132
+ """ZAI转换器类"""
133
+
134
+ def __init__(self):
135
+ """初始化转换器"""
136
+ self.name = "zai"
137
+ self.base_url = "https://chat.z.ai"
138
+ self.api_url = settings.API_ENDPOINT
139
+ self.auth_url = f"{self.base_url}/api/v1/auths/"
140
+
141
+ # 模型映射
142
+ self.model_mapping = {
143
+ settings.PRIMARY_MODEL: "0727-360B-API", # GLM-4.5
144
+ settings.THINKING_MODEL: "0727-360B-API", # GLM-4.5-Thinking
145
+ settings.SEARCH_MODEL: "0727-360B-API", # GLM-4.5-Search
146
+ settings.AIR_MODEL: "0727-106B-API", # GLM-4.5-Air
147
+ }
148
+
149
+ async def get_token(self) -> str:
150
+ """异步获取认证令牌"""
151
+ if settings.ANONYMOUS_MODE:
152
+ try:
153
+
154
+ headers = get_dynamic_headers()
155
+ async with httpx.AsyncClient() as client:
156
+ response = await client.get(self.auth_url, headers=headers, timeout=10.0)
157
+ if response.status_code == 200:
158
+ data = response.json()
159
+ token = data.get("token", "")
160
+ if token:
161
+ logger.debug(f"获取访客令牌成功: {token[:20]}...")
162
+ return token
163
+ except Exception as e:
164
+ logger.warning(f"异步获取访客令牌失败: {e}")
165
+
166
+ # 使用token池获取备份令牌
167
+ token_pool = get_token_pool()
168
+ if token_pool:
169
+ token = token_pool.get_next_token()
170
+ if token:
171
+ logger.debug(f"从token池获取令牌: {token[:20]}...")
172
+ return token
173
+
174
+ # 没有可用的token
175
+ logger.warning("⚠️ 没有可用的备份token")
176
+ return ""
177
+
178
+ def mark_token_success(self, token: str):
179
+ """标记token使用成功"""
180
+ token_pool = get_token_pool()
181
+ if token_pool:
182
+ token_pool.mark_token_success(token)
183
+
184
+ def mark_token_failure(self, token: str, error: Exception = None):
185
+ """标记token使用失败"""
186
+ token_pool = get_token_pool()
187
+ if token_pool:
188
+ token_pool.mark_token_failure(token, error)
189
+
190
+ async def transform_request_in(self, request: Dict[str, Any]) -> Dict[str, Any]:
191
+ """
192
+ 转换OpenAI请求为z.ai格式
193
+ 整合现有功能:模型映射、MCP服务器等
194
+ """
195
+ logger.info(f"🔄 开始转换 OpenAI 请求到 Z.AI 格式: {request.get('model', settings.PRIMARY_MODEL)} -> Z.AI")
196
+
197
+ # 获取认证令牌
198
+ token = await self.get_token()
199
+ logger.debug(f" 使用令牌: {token[:20] if token else 'None'}...")
200
+
201
+ # 检查token是否有效
202
+ if not token:
203
+ logger.error("❌ 无法获取有效的认证令牌")
204
+ raise Exception("无法获取有效的认证令牌,请检查匿名模式配置或token池配置")
205
+
206
+ # 确定请求的模型特性
207
+ requested_model = request.get("model", settings.PRIMARY_MODEL)
208
+ is_thinking = requested_model == settings.THINKING_MODEL or request.get("reasoning", False)
209
+ is_search = requested_model == settings.SEARCH_MODEL
210
+ is_air = requested_model == settings.AIR_MODEL
211
+
212
+ # 获取上游模型ID(使用模型映射)
213
+ upstream_model_id = self.model_mapping.get(requested_model, "0727-360B-API")
214
+ logger.debug(f" 模型映射: {requested_model} -> {upstream_model_id}")
215
+ logger.debug(f" 模型特性检测: is_search={is_search}, is_thinking={is_thinking}, is_air={is_air}")
216
+ logger.debug(f" SEARCH_MODEL配置: {settings.SEARCH_MODEL}")
217
+
218
+ # 处理消息列表
219
+ logger.debug(f" 开始处理 {len(request.get('messages', []))} 条消息")
220
+ messages = []
221
+ for idx, orig_msg in enumerate(request.get("messages", [])):
222
+ msg = orig_msg.copy()
223
+
224
+ # 处理system角色转换
225
+ if msg.get("role") == "system":
226
+
227
+ msg["role"] = "user"
228
+ content = msg.get("content")
229
+
230
+ if isinstance(content, list):
231
+ msg["content"] = [
232
+ {"type": "text", "text": "This is a system command, you must enforce compliance."}
233
+ ] + content
234
+ elif isinstance(content, str):
235
+ msg["content"] = f"This is a system command, you must enforce compliance.{content}"
236
+
237
+ # 处理user角色的图片内容
238
+ elif msg.get("role") == "user":
239
+ content = msg.get("content")
240
+ if isinstance(content, list):
241
+ new_content = []
242
+ for part_idx, part in enumerate(content):
243
+ # 处理图片URL(支持base64和http URL)
244
+ if (
245
+ part.get("type") == "image_url"
246
+ and part.get("image_url", {}).get("url")
247
+ and isinstance(part["image_url"]["url"], str)
248
+ ):
249
+ logger.debug(f" 消息[{idx}]内容[{part_idx}]: 检测到图片URL")
250
+ # 直接传递图片内容
251
+ new_content.append(part)
252
+ else:
253
+ new_content.append(part)
254
+ msg["content"] = new_content
255
+
256
+ # 处理assistant消息中的reasoning_content
257
+ elif msg.get("role") == "assistant" and msg.get("reasoning_content"):
258
+
259
+ # 如果有reasoning_content,保留它
260
+ pass
261
+
262
+ messages.append(msg)
263
+
264
+ # 构建MCP服务器列表
265
+ mcp_servers = []
266
+ if is_search:
267
+ mcp_servers.append("deep-web-search")
268
+ logger.info(f"🔍 检测到搜索模型,添加 deep-web-search MCP 服务器")
269
+ else:
270
+ logger.debug(f" 非搜索模型,不添加 MCP ��务器")
271
+
272
+ logger.debug(f" MCP服务器列表: {mcp_servers}")
273
+
274
+ # 构建上游请求体
275
+ chat_id = generate_uuid()
276
+
277
+ body = {
278
+ "stream": True, # 总是使用流式
279
+ "model": upstream_model_id, # 使用映射后的模型ID
280
+ "messages": messages,
281
+ "params": {},
282
+ "features": {
283
+ "image_generation": False,
284
+ "web_search": is_search,
285
+ "auto_web_search": is_search,
286
+ "preview_mode": False,
287
+ "flags": [],
288
+ "features": [],
289
+ "enable_thinking": is_thinking,
290
+ },
291
+ "background_tasks": {
292
+ "title_generation": False,
293
+ "tags_generation": False,
294
+ },
295
+ "mcp_servers": mcp_servers, # 保留MCP服务器支持
296
+ "variables": {
297
+ "{{USER_NAME}}": "Guest",
298
+ "{{USER_LOCATION}}": "Unknown",
299
+ "{{CURRENT_DATETIME}}": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
300
+ "{{CURRENT_DATE}}": datetime.now().strftime("%Y-%m-%d"),
301
+ "{{CURRENT_TIME}}": datetime.now().strftime("%H:%M:%S"),
302
+ "{{CURRENT_WEEKDAY}}": datetime.now().strftime("%A"),
303
+ "{{CURRENT_TIMEZONE}}": "UTC",
304
+ "{{USER_LANGUAGE}}": "zh-CN",
305
+ },
306
+ "model_item": {},
307
+ "chat_id": chat_id,
308
+ "id": generate_uuid(),
309
+ }
310
+
311
+ # 处理工具支持
312
+ if settings.TOOL_SUPPORT and not is_thinking and request.get("tools"):
313
+ body["tools"] = request["tools"]
314
+ logger.info(f"启用工具支持: {len(request['tools'])} 个工具")
315
+ else:
316
+ body["tools"] = None
317
+
318
+ # 构建请求配置
319
+ dynamic_headers = get_dynamic_headers(chat_id)
320
+
321
+ config = {
322
+ "url": self.api_url, # 使用原始URL
323
+ "headers": {
324
+ **dynamic_headers, # 使用动态生成的headers
325
+ "Authorization": f"Bearer {token}",
326
+ "Cache-Control": "no-cache",
327
+ "Connection": "keep-alive",
328
+ "Pragma": "no-cache",
329
+ "Sec-Fetch-Dest": "empty",
330
+ "Sec-Fetch-Mode": "cors",
331
+ "Sec-Fetch-Site": "same-origin",
332
+ },
333
+ }
334
+
335
+ logger.info("✅ 请求转换完成")
336
+
337
+ # 记录关键的请求信息用于调试
338
+ logger.debug(f" 📋 发送到Z.AI的关键信息:")
339
+ logger.debug(f" - 上游模型: {body['model']}")
340
+ logger.debug(f" - MCP服务器: {body['mcp_servers']}")
341
+ logger.debug(f" - web_search: {body['features']['web_search']}")
342
+ logger.debug(f" - auto_web_search: {body['features']['auto_web_search']}")
343
+ logger.debug(f" - 消息数量: {len(body['messages'])}")
344
+
345
+ return {"body": body, "config": config, "token": token}
346
+
347
+ async def transform_response_out(
348
+ self, response_stream: Generator, context: Dict[str, Any]
349
+ ) -> Generator[str, None, None]:
350
+ """
351
+ 转换z.ai响应为OpenAI格式
352
+ 支持流式和非流式输出
353
+ """
354
+ is_stream = context.get("req", {}).get("body", {}).get("stream", True)
355
+
356
+ # 初始化结果对象(用于非流式)
357
+ result = {
358
+ "id": "",
359
+ "choices": [
360
+ {
361
+ "finish_reason": None,
362
+ "index": 0,
363
+ "message": {
364
+ "content": "",
365
+ "role": "assistant",
366
+ },
367
+ }
368
+ ],
369
+ "created": int(time.time()),
370
+ "model": context.get("req", {}).get("body", {}).get("model", ""),
371
+ "object": "chat.completion",
372
+ "usage": {
373
+ "completion_tokens": 0,
374
+ "prompt_tokens": 0,
375
+ "total_tokens": 0,
376
+ },
377
+ }
378
+
379
+ # 状态变量
380
+ current_id = ""
381
+ current_model = context.get("req", {}).get("body", {}).get("model", "")
382
+ has_tool_call = False
383
+ tool_args = ""
384
+ tool_id = ""
385
+ tool_call_usage = None
386
+ content_index = 0
387
+ has_thinking = False
388
+
389
+ async for line in response_stream:
390
+ if not line.strip():
391
+ continue
392
+
393
+ if line.startswith("data:"):
394
+ chunk_str = line[5:].strip()
395
+ if not chunk_str:
396
+ continue
397
+
398
+ try:
399
+ chunk = json.loads(chunk_str)
400
+
401
+ if chunk.get("type") == "chat:completion":
402
+ data = chunk.get("data", {})
403
+
404
+ # 保存ID和模型信息
405
+ if data.get("id"):
406
+ current_id = data["id"]
407
+ if data.get("model"):
408
+ current_model = data["model"]
409
+
410
+ # 处理不同阶段
411
+ phase = data.get("phase")
412
+
413
+ if phase == "tool_call":
414
+ # 处理工具调用
415
+ if not has_tool_call:
416
+ has_tool_call = True
417
+
418
+ if is_stream:
419
+ # 发送初始角色
420
+ role_chunk = {
421
+ "choices": [
422
+ {
423
+ "delta": {"role": "assistant"},
424
+ "finish_reason": None,
425
+ "index": 0,
426
+ }
427
+ ],
428
+ "created": int(time.time()),
429
+ "id": current_id,
430
+ "model": current_model,
431
+ "object": "chat.completion.chunk",
432
+ }
433
+ yield f"data: {json.dumps(role_chunk)}\n\n"
434
+
435
+ # 处理工具调用块
436
+ tool_call_id = data.get("tool_call", {}).get("id", "")
437
+ tool_name = data.get("tool_call", {}).get("name", "")
438
+ delta_args = data.get("delta_tool_call", {}).get("arguments", "")
439
+
440
+ if tool_call_id and tool_call_id != tool_id:
441
+ # 新工具调用
442
+ if tool_id and is_stream:
443
+ # 关闭前一个工具调用
444
+ close_chunk = {
445
+ "choices": [
446
+ {
447
+ "delta": {
448
+ "tool_calls": [
449
+ {"index": content_index, "function": {"arguments": ""}}
450
+ ]
451
+ },
452
+ "finish_reason": None,
453
+ "index": 0,
454
+ }
455
+ ],
456
+ "created": int(time.time()),
457
+ "id": current_id,
458
+ "model": current_model,
459
+ "object": "chat.completion.chunk",
460
+ }
461
+ yield f"data: {json.dumps(close_chunk)}\n\n"
462
+ content_index += 1
463
+
464
+ tool_id = tool_call_id
465
+ tool_args = ""
466
+
467
+ if is_stream:
468
+ # 发送新工具调用
469
+ new_tool_chunk = {
470
+ "choices": [
471
+ {
472
+ "delta": {
473
+ "tool_calls": [
474
+ {
475
+ "index": content_index,
476
+ "id": tool_call_id,
477
+ "type": "function",
478
+ "function": {"name": tool_name, "arguments": ""},
479
+ }
480
+ ]
481
+ },
482
+ "finish_reason": None,
483
+ "index": 0,
484
+ }
485
+ ],
486
+ "created": int(time.time()),
487
+ "id": current_id,
488
+ "model": current_model,
489
+ "object": "chat.completion.chunk",
490
+ }
491
+ yield f"data: {json.dumps(new_tool_chunk)}\n\n"
492
+
493
+ # 处理参数增量
494
+ if delta_args:
495
+ tool_args += delta_args
496
+ if is_stream:
497
+ args_chunk = {
498
+ "choices": [
499
+ {
500
+ "delta": {
501
+ "tool_calls": [
502
+ {
503
+ "index": content_index,
504
+ "function": {"arguments": delta_args},
505
+ }
506
+ ]
507
+ },
508
+ "finish_reason": None,
509
+ "index": 0,
510
+ }
511
+ ],
512
+ "created": int(time.time()),
513
+ "id": current_id,
514
+ "model": current_model,
515
+ "object": "chat.completion.chunk",
516
+ }
517
+ yield f"data: {json.dumps(args_chunk)}\n\n"
518
+
519
+ elif phase == "thinking":
520
+ # 处理思考内容
521
+ if not has_thinking:
522
+ has_thinking = True
523
+ # 初始化thinking字段
524
+ if not is_stream:
525
+ result["choices"][0]["message"]["thinking"] = {"content": ""}
526
+
527
+ if is_stream:
528
+ # 发送初始角色
529
+ role_chunk = {
530
+ "choices": [
531
+ {
532
+ "delta": {"role": "assistant"},
533
+ "finish_reason": None,
534
+ "index": 0,
535
+ }
536
+ ],
537
+ "created": int(time.time()),
538
+ "id": current_id,
539
+ "model": current_model,
540
+ "object": "chat.completion.chunk",
541
+ }
542
+ yield f"data: {json.dumps(role_chunk)}\n\n"
543
+
544
+ delta_content = data.get("delta_content", "")
545
+ if delta_content:
546
+ # 处理思考内容格式
547
+ if delta_content.startswith("<details"):
548
+ content = (
549
+ delta_content.split("</summary>\n>")[-1].strip()
550
+ if "</summary>\n>" in delta_content
551
+ else delta_content
552
+ )
553
+ else:
554
+ content = delta_content
555
+
556
+ if is_stream:
557
+ thinking_chunk = {
558
+ "choices": [
559
+ {
560
+ "delta": {"thinking": {"content": content}},
561
+ "finish_reason": None,
562
+ "index": 0,
563
+ }
564
+ ],
565
+ "created": int(time.time()),
566
+ "id": current_id,
567
+ "model": current_model,
568
+ "object": "chat.completion.chunk",
569
+ }
570
+ yield f"data: {json.dumps(thinking_chunk)}\n\n"
571
+ else:
572
+ result["choices"][0]["message"]["thinking"]["content"] += content
573
+
574
+ elif phase == "answer":
575
+ # 处理答案内容
576
+ edit_content = data.get("edit_content", "")
577
+ delta_content = data.get("delta_content", "")
578
+
579
+ # 处理思考结束和答案开始
580
+ if edit_content and "</details>\n" in edit_content:
581
+ if has_thinking:
582
+ signature = str(int(time.time() * 1000))
583
+
584
+ if is_stream:
585
+ # 发送思考签名
586
+ sig_chunk = {
587
+ "choices": [
588
+ {
589
+ "delta": {
590
+ "role": "assistant",
591
+ "thinking": {"content": "", "signature": signature},
592
+ },
593
+ "finish_reason": None,
594
+ "index": 0,
595
+ }
596
+ ],
597
+ "created": int(time.time()),
598
+ "id": current_id,
599
+ "model": current_model,
600
+ "object": "chat.completion.chunk",
601
+ }
602
+ yield f"data: {json.dumps(sig_chunk)}\n\n"
603
+ content_index += 1
604
+ else:
605
+ result["choices"][0]["message"]["thinking"]["signature"] = signature
606
+
607
+ # 提取答案内容
608
+ content_after = edit_content.split("</details>\n")[-1]
609
+ if content_after:
610
+ if is_stream:
611
+ content_chunk = {
612
+ "choices": [
613
+ {
614
+ "delta": {"role": "assistant", "content": content_after},
615
+ "finish_reason": None,
616
+ "index": 0,
617
+ }
618
+ ],
619
+ "created": int(time.time()),
620
+ "id": current_id,
621
+ "model": current_model,
622
+ "object": "chat.completion.chunk",
623
+ }
624
+ yield f"data: {json.dumps(content_chunk)}\n\n"
625
+ else:
626
+ result["choices"][0]["message"]["content"] += content_after
627
+
628
+ # 处理增量内容
629
+ elif delta_content:
630
+ if is_stream:
631
+ # 如果还没有发送角色
632
+ if not has_thinking and not has_tool_call:
633
+ role_chunk = {
634
+ "choices": [
635
+ {
636
+ "delta": {"role": "assistant"},
637
+ "finish_reason": None,
638
+ "index": 0,
639
+ }
640
+ ],
641
+ "created": int(time.time()),
642
+ "id": current_id,
643
+ "model": current_model,
644
+ "object": "chat.completion.chunk",
645
+ }
646
+ yield f"data: {json.dumps(role_chunk)}\n\n"
647
+
648
+ content_chunk = {
649
+ "choices": [
650
+ {
651
+ "delta": {"role": "assistant", "content": delta_content},
652
+ "finish_reason": None,
653
+ "index": 0,
654
+ }
655
+ ],
656
+ "created": int(time.time()),
657
+ "id": current_id,
658
+ "model": current_model,
659
+ "object": "chat.completion.chunk",
660
+ }
661
+ yield f"data: {json.dumps(content_chunk)}\n\n"
662
+ else:
663
+ result["choices"][0]["message"]["content"] += delta_content
664
+
665
+ # 处理完成
666
+ if data.get("usage"):
667
+ usage = data["usage"]
668
+ if is_stream:
669
+ finish_chunk = {
670
+ "choices": [
671
+ {
672
+ "delta": {"role": "assistant", "content": ""},
673
+ "finish_reason": "stop",
674
+ "index": 0,
675
+ }
676
+ ],
677
+ "usage": usage,
678
+ "created": int(time.time()),
679
+ "id": current_id,
680
+ "model": current_model,
681
+ "object": "chat.completion.chunk",
682
+ }
683
+ yield f"data: {json.dumps(finish_chunk)}\n\n"
684
+ yield "data: [DONE]\n\n"
685
+ else:
686
+ result["id"] = current_id
687
+ result["model"] = current_model
688
+ result["usage"] = usage
689
+ result["choices"][0]["finish_reason"] = "stop"
690
+
691
+ elif phase == "other":
692
+ # 处理其他阶段(可能包含usage信息)
693
+ if data.get("usage"):
694
+ tool_call_usage = data["usage"]
695
+ if has_tool_call and is_stream:
696
+ # 关闭最后一个工具调用并发送完成
697
+ if tool_id:
698
+ close_chunk = {
699
+ "choices": [
700
+ {
701
+ "delta": {
702
+ "tool_calls": [
703
+ {"index": content_index, "function": {"arguments": ""}}
704
+ ]
705
+ },
706
+ "finish_reason": "tool_calls",
707
+ "index": 0,
708
+ }
709
+ ],
710
+ "usage": tool_call_usage,
711
+ "created": int(time.time()),
712
+ "id": current_id,
713
+ "model": current_model,
714
+ "object": "chat.completion.chunk",
715
+ }
716
+ yield f"data: {json.dumps(close_chunk)}\n\n"
717
+ yield "data: [DONE]\n\n"
718
+
719
+ except json.JSONDecodeError as e:
720
+ logger.debug(f"JSON解析错误: {e}")
721
+ except Exception as e:
722
+ logger.error(f"处理chunk错误: {e}")
723
+
724
+ # 非流式模式返回完整结果
725
+ if not is_stream:
726
+ yield json.dumps(result)
app/models/__init__.py CHANGED
@@ -1,7 +1,6 @@
1
- """
2
- Models module initialization
3
- """
4
 
5
  from app.models import schemas
6
 
7
- __all__ = ["schemas"]
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
  from app.models import schemas
5
 
6
+ __all__ = ["schemas"]
app/models/schemas.py CHANGED
@@ -1,6 +1,5 @@
1
- """
2
- Application data models
3
- """
4
 
5
  from typing import Dict, List, Optional, Any, Union, Literal
6
  from pydantic import BaseModel
@@ -54,8 +53,8 @@ class UpstreamRequest(BaseModel):
54
  chat_id: Optional[str] = None
55
  id: Optional[str] = None
56
  mcp_servers: Optional[List[str]] = None
57
- model_item: Optional[ModelItem] = None
58
- tool_servers: Optional[List[str]] = None
59
  variables: Optional[Dict[str, str]] = None
60
  model_config = {"protected_namespaces": ()}
61
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
  from typing import Dict, List, Optional, Any, Union, Literal
5
  from pydantic import BaseModel
 
53
  chat_id: Optional[str] = None
54
  id: Optional[str] = None
55
  mcp_servers: Optional[List[str]] = None
56
+ model_item: Optional[Dict[str, Any]] = {} # Model item dictionary
57
+ tools: Optional[List[Dict[str, Any]]] = None # Add tools field for OpenAI compatibility
58
  variables: Optional[Dict[str, str]] = None
59
  model_config = {"protected_namespaces": ()}
60
 
app/utils/__init__.py CHANGED
@@ -1,7 +1,6 @@
1
- """
2
- Utils module initialization
3
- """
4
 
5
- from app.utils import helpers, sse_parser, tools, reload_config
6
 
7
- __all__ = ["helpers", "sse_parser", "tools", "reload_config"]
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
 
3
 
4
+ from app.utils import sse_tool_handler, reload_config, logger
5
 
6
+ __all__ = ["sse_tool_handler", "reload_config", "logger"]
app/utils/helpers.py DELETED
@@ -1,211 +0,0 @@
1
- """
2
- Utility functions for the application
3
- """
4
-
5
- import json
6
- import re
7
- import time
8
- import random
9
- from typing import Dict, List, Optional, Any, Tuple, Generator
10
- import requests
11
- from fake_useragent import UserAgent
12
-
13
- from app.core.config import settings
14
-
15
- # 全局 UserAgent 实例,避免每次调用都创建新实例
16
- _user_agent_instance = None
17
-
18
- def get_user_agent_instance() -> UserAgent:
19
- """获取或创建 UserAgent 实例(单例模式)"""
20
- global _user_agent_instance
21
- if _user_agent_instance is None:
22
- _user_agent_instance = UserAgent()
23
- return _user_agent_instance
24
-
25
-
26
- def debug_log(message: str, *args) -> None:
27
- """Log debug message if debug mode is enabled"""
28
- if settings.DEBUG_LOGGING:
29
- if args:
30
- print(f"[DEBUG] {message % args}")
31
- else:
32
- print(f"[DEBUG] {message}")
33
-
34
-
35
- def generate_request_ids() -> Tuple[str, str]:
36
- """Generate unique IDs for chat and message"""
37
- timestamp = int(time.time())
38
- chat_id = f"{timestamp * 1000}-{timestamp}"
39
- msg_id = str(timestamp * 1000000)
40
- return chat_id, msg_id
41
-
42
-
43
- def get_browser_headers(referer_chat_id: str = "") -> Dict[str, str]:
44
- """Get browser headers for API requests with dynamic User-Agent"""
45
-
46
- # 获取 UserAgent 实例
47
- ua = get_user_agent_instance()
48
-
49
- # 随机选择一个浏览器类型,偏向使用 Chrome 和 Edge
50
- browser_choices = ['chrome', 'chrome', 'chrome', 'edge', 'edge', 'firefox', 'safari']
51
- browser_type = random.choice(browser_choices)
52
-
53
- try:
54
- # 根据浏览器类型获取 User-Agent
55
- if browser_type == 'chrome':
56
- user_agent = ua.chrome
57
- elif browser_type == 'edge':
58
- user_agent = ua.edge
59
- elif browser_type == 'firefox':
60
- user_agent = ua.firefox
61
- elif browser_type == 'safari':
62
- user_agent = ua.safari
63
- else:
64
- user_agent = ua.random
65
- except:
66
- # 如果获取失败,使用随机 User-Agent
67
- user_agent = ua.random
68
-
69
- # 提取浏览器版本信息
70
- chrome_version = "139" # 默认版本
71
- edge_version = "139"
72
-
73
- if "Chrome/" in user_agent:
74
- try:
75
- chrome_version = user_agent.split("Chrome/")[1].split(".")[0]
76
- except:
77
- pass
78
-
79
- if "Edg/" in user_agent:
80
- try:
81
- edge_version = user_agent.split("Edg/")[1].split(".")[0]
82
- # Edge 基于 Chromium,使用 Edge 特定的 sec-ch-ua
83
- sec_ch_ua = f'"Microsoft Edge";v="{edge_version}", "Chromium";v="{chrome_version}", "Not_A Brand";v="24"'
84
- except:
85
- sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
86
- elif "Firefox/" in user_agent:
87
- # Firefox 不使用 sec-ch-ua
88
- sec_ch_ua = None
89
- else:
90
- # Chrome 或其他基于 Chromium 的浏览器
91
- sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
92
-
93
- # 构建动态 Headers
94
- headers = {
95
- "Content-Type": "application/json",
96
- "Accept": "application/json, text/event-stream",
97
- "User-Agent": user_agent,
98
- "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8,en-US;q=0.7",
99
- "sec-ch-ua-mobile": "?0",
100
- "sec-ch-ua-platform": '"Windows"',
101
- "sec-fetch-dest": "empty",
102
- "sec-fetch-mode": "cors",
103
- "sec-fetch-site": "same-origin",
104
- "X-FE-Version": "prod-fe-1.0.70",
105
- "Origin": settings.CLIENT_HEADERS["Origin"],
106
- "Cache-Control": "no-cache",
107
- "Pragma": "no-cache",
108
- }
109
-
110
- # 只有基于 Chromium 的浏览器才添加 sec-ch-ua
111
- if sec_ch_ua:
112
- headers["sec-ch-ua"] = sec_ch_ua
113
-
114
- # 添加 Referer
115
- if referer_chat_id:
116
- headers["Referer"] = f"{settings.CLIENT_HEADERS['Origin']}/c/{referer_chat_id}"
117
-
118
- # 调试日志
119
- if settings.DEBUG_LOGGING:
120
- debug_log(f"使用 User-Agent: {user_agent[:100]}...")
121
-
122
- return headers
123
-
124
-
125
- def get_anonymous_token() -> str:
126
- """Get anonymous token for authentication"""
127
- headers = get_browser_headers()
128
- headers.update({
129
- "Accept": "*/*",
130
- "Accept-Language": "zh-CN,zh;q=0.9",
131
- "Referer": f"{settings.CLIENT_HEADERS['Origin']}/",
132
- })
133
-
134
- try:
135
- response = requests.get(
136
- f"{settings.CLIENT_HEADERS['Origin']}/api/v1/auths/",
137
- headers=headers,
138
- timeout=10.0
139
- )
140
-
141
- if response.status_code != 200:
142
- raise Exception(f"anon token status={response.status_code}")
143
-
144
- data = response.json()
145
- token = data.get("token")
146
- if not token:
147
- raise Exception("anon token empty")
148
-
149
- return token
150
- except Exception as e:
151
- debug_log(f"获取匿名token失败: {e}")
152
- raise
153
-
154
-
155
- def get_auth_token() -> str:
156
- """Get authentication token (anonymous or fixed)"""
157
- if settings.ANONYMOUS_MODE:
158
- try:
159
- token = get_anonymous_token()
160
- debug_log(f"匿名token获取成功: {token[:10]}...")
161
- return token
162
- except Exception as e:
163
- debug_log(f"匿名token获取失败,回退固定token: {e}")
164
-
165
- return settings.BACKUP_TOKEN
166
-
167
-
168
- def transform_thinking_content(content: str) -> str:
169
- """Transform thinking content according to configuration"""
170
- # Remove summary tags
171
- content = re.sub(r'(?s)<summary>.*?</summary>', '', content)
172
- # Clean up remaining tags
173
- content = content.replace("</thinking>", "").replace("<Full>", "").replace("</Full>", "")
174
- content = content.strip()
175
-
176
- if settings.THINKING_PROCESSING == "think":
177
- content = re.sub(r'<details[^>]*>', '<span>', content)
178
- content = content.replace("</details>", "</span>")
179
- elif settings.THINKING_PROCESSING == "strip":
180
- content = re.sub(r'<details[^>]*>', '', content)
181
- content = content.replace("</details>", "")
182
-
183
- # Remove line prefixes
184
- content = content.lstrip("> ")
185
- content = content.replace("\n> ", "\n")
186
-
187
- return content.strip()
188
-
189
-
190
- def call_upstream_api(
191
- upstream_req: Any,
192
- chat_id: str,
193
- auth_token: str
194
- ) -> requests.Response:
195
- """Call upstream API with proper headers"""
196
- headers = get_browser_headers(chat_id)
197
- headers["Authorization"] = f"Bearer {auth_token}"
198
-
199
- debug_log(f"调用上游API: {settings.API_ENDPOINT}")
200
- debug_log(f"上游请求体: {upstream_req.model_dump_json()}")
201
-
202
- response = requests.post(
203
- settings.API_ENDPOINT,
204
- json=upstream_req.model_dump(exclude_none=True),
205
- headers=headers,
206
- timeout=60.0,
207
- stream=True
208
- )
209
-
210
- debug_log(f"上游响应状态: {response.status_code}")
211
- return response
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/utils/logger.py ADDED
@@ -0,0 +1,104 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ import sys
5
+ from pathlib import Path
6
+ from loguru import logger
7
+
8
+ # Global logger instance
9
+ app_logger = None
10
+
11
+
12
+ def setup_logger(log_dir, log_retention_days=7, log_rotation="1 day", debug_mode=False):
13
+ """
14
+ Create a logger instance
15
+
16
+ Parameters:
17
+ log_dir (str): 日志目录
18
+ log_retention_days (int): 日志保留天数
19
+ log_rotation (str): 日志轮转间隔
20
+ debug_mode (bool): 是否开启调试模式
21
+ """
22
+ global app_logger
23
+
24
+ try:
25
+ logger.remove()
26
+
27
+ log_level = "DEBUG" if debug_mode else "INFO"
28
+
29
+ console_format = (
30
+ "<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <level>{message}</level>"
31
+ if not debug_mode
32
+ else "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
33
+ "<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | <level>{message}</level>"
34
+ )
35
+
36
+ logger.add(sys.stderr, level=log_level, format=console_format, colorize=True)
37
+
38
+ if debug_mode:
39
+ log_path = Path(log_dir)
40
+ log_path.mkdir(parents=True, exist_ok=True)
41
+
42
+ log_file = log_path / "{time:YYYY-MM-DD}.log"
43
+ file_format = "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {message}"
44
+
45
+ logger.add(
46
+ str(log_file),
47
+ level=log_level,
48
+ format=file_format,
49
+ rotation=log_rotation,
50
+ retention=f"{log_retention_days} days",
51
+ encoding="utf-8",
52
+ compression="zip",
53
+ enqueue=True,
54
+ catch=True,
55
+ )
56
+
57
+ app_logger = logger
58
+
59
+ return logger
60
+
61
+ except Exception as e:
62
+ logger.remove()
63
+ logger.add(sys.stderr, level="ERROR")
64
+ logger.error(f"日志系统配置失败: {e}")
65
+ raise
66
+
67
+
68
+ def get_logger():
69
+ """Get the logger instance"""
70
+ global app_logger
71
+ if app_logger is None:
72
+
73
+ app_logger = logger
74
+ logger.add(sys.stderr, level="INFO")
75
+ return app_logger
76
+
77
+
78
+ if __name__ == "__main__":
79
+ """Test the logger"""
80
+ import tempfile
81
+
82
+ with tempfile.TemporaryDirectory() as temp_dir:
83
+ try:
84
+ setup_logger(temp_dir, debug_mode=True)
85
+
86
+ logger.debug("这是一条调试日志")
87
+ logger.info("这是一条信息日志")
88
+ logger.warning("这是一条警告日志")
89
+ logger.error("这是一条错误日志")
90
+ logger.critical("这是一条严重日志")
91
+
92
+ try:
93
+ 1 / 0
94
+ except ZeroDivisionError:
95
+ logger.exception("发生了除零异常")
96
+
97
+ print("✅ 日志测试完成")
98
+
99
+ logger.remove()
100
+
101
+ except Exception as e:
102
+ print(f"❌ 日志测试失败: {e}")
103
+ logger.remove()
104
+ raise
app/utils/reload_config.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  """
2
  热重载配置模块
3
  定义 Granian 服务器热重载时需要忽略的目录和文件模式
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
  """
5
  热重载配置模块
6
  定义 Granian 服务器热重载时需要忽略的目录和文件模式
app/utils/sse_parser.py DELETED
@@ -1,127 +0,0 @@
1
- """
2
- SSE (Server-Sent Events) parser for streaming responses
3
- """
4
-
5
- import json
6
- from typing import Dict, Any, Generator, Optional, Type
7
- import requests
8
-
9
-
10
- class SSEParser:
11
- """Server-Sent Events parser for streaming responses"""
12
-
13
- def __init__(self, response: requests.Response, debug_mode: bool = False):
14
- """Initialize SSE parser
15
-
16
- Args:
17
- response: requests.Response object with stream=True
18
- debug_mode: Enable debug logging
19
- """
20
- self.response = response
21
- self.debug_mode = debug_mode
22
- self.buffer = ""
23
- self.line_count = 0
24
-
25
- def debug_log(self, format_str: str, *args) -> None:
26
- """Log debug message if debug mode is enabled"""
27
- if self.debug_mode:
28
- if args:
29
- print(f"[SSE_PARSER] {format_str % args}")
30
- else:
31
- print(f"[SSE_PARSER] {format_str}")
32
-
33
- def iter_events(self) -> Generator[Dict[str, Any], None, None]:
34
- """Iterate over SSE events
35
-
36
- Yields:
37
- dict: Parsed SSE event data
38
- """
39
- self.debug_log("开始解析 SSE 流")
40
-
41
- for line in self.response.iter_lines():
42
- self.line_count += 1
43
-
44
- # Skip empty lines
45
- if not line:
46
- continue
47
-
48
- # Decode bytes
49
- if isinstance(line, bytes):
50
- try:
51
- line = line.decode("utf-8")
52
- except UnicodeDecodeError:
53
- self.debug_log(f"第{self.line_count}行解码失败,跳过")
54
- continue
55
-
56
- # Skip comment lines
57
- if line.startswith(":"):
58
- continue
59
-
60
- # Parse field-value pairs
61
- if ":" in line:
62
- field, value = line.split(":", 1)
63
- field = field.strip()
64
- value = value.lstrip()
65
-
66
- if field == "data":
67
- self.debug_log(f"收到数据 (第{self.line_count}行): {value}")
68
-
69
- # Try to parse JSON
70
- try:
71
- data = json.loads(value)
72
- yield {"type": "data", "data": data, "raw": value}
73
- except json.JSONDecodeError:
74
- yield {"type": "data", "data": value, "raw": value, "is_json": False}
75
-
76
- elif field == "event":
77
- yield {"type": "event", "event": value}
78
-
79
- elif field == "id":
80
- yield {"type": "id", "id": value}
81
-
82
- elif field == "retry":
83
- try:
84
- retry = int(value)
85
- yield {"type": "retry", "retry": retry}
86
- except ValueError:
87
- self.debug_log(f"无效的 retry 值: {value}")
88
-
89
- def iter_data_only(self) -> Generator[Dict[str, Any], None, None]:
90
- """Iterate only over data events"""
91
- for event in self.iter_events():
92
- if event["type"] == "data":
93
- yield event
94
-
95
- def iter_json_data(self, model_class: Optional[Type] = None) -> Generator[Dict[str, Any], None, None]:
96
- """Iterate only over JSON data events with optional validation
97
-
98
- Args:
99
- model_class: Optional Pydantic model class for validation
100
-
101
- Yields:
102
- dict: JSON data events
103
- """
104
- for event in self.iter_events():
105
- if event["type"] == "data" and event.get("is_json", True):
106
- try:
107
- if model_class:
108
- data = model_class.model_validate_json(event["raw"])
109
- yield {"type": "data", "data": data, "raw": event["raw"]}
110
- else:
111
- yield event
112
- except Exception as e:
113
- self.debug_log(f"数据验证失败: {e}")
114
- continue
115
-
116
- def close(self) -> None:
117
- """Close the response connection"""
118
- if hasattr(self.response, "close"):
119
- self.response.close()
120
-
121
- def __enter__(self):
122
- """Context manager entry"""
123
- return self
124
-
125
- def __exit__(self, exc_type, exc_val, exc_tb) -> None:
126
- """Context manager exit"""
127
- self.close()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
app/utils/sse_tool_handler.py ADDED
@@ -0,0 +1,694 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ SSE Tool Handler - 处理工具调用的SSE流
6
+ 基于 Z.AI 原生的 edit_index 和 edit_content 机制,更原生地处理工具调用
7
+ """
8
+
9
+ import json
10
+ import re
11
+ import time
12
+ from typing import Dict, Any, Optional, Generator, List
13
+
14
+ from app.utils.logger import get_logger
15
+
16
+ logger = get_logger()
17
+
18
+
19
+ class SSEToolHandler:
20
+
21
+ def __init__(self, chat_id: str, model: str):
22
+ self.chat_id = chat_id
23
+ self.model = model
24
+
25
+ # 工具调用状态
26
+ self.has_tool_call = False
27
+ self.tool_call_usage = None # 工具调用的usage信息
28
+ self.content_index = 0
29
+ self.has_thinking = False
30
+
31
+ self.content_buffer = bytearray() # 使用字节数组提高性能
32
+ self.last_edit_index = 0 # 上次编辑的位置
33
+
34
+ # 工具调用解析状态
35
+ self.active_tools = {} # 活跃的工具调用 {tool_id: tool_info}
36
+ self.completed_tools = [] # 已完成的工具调用
37
+ self.tool_blocks_cache = {} # 缓存解析的工具块
38
+
39
+ def process_tool_call_phase(self, data: Dict[str, Any], is_stream: bool = True) -> Generator[str, None, None]:
40
+ """
41
+ 处理tool_call阶段
42
+ """
43
+ if not self.has_tool_call:
44
+ self.has_tool_call = True
45
+ logger.debug("🔧 进入工具调用阶段")
46
+
47
+ edit_content = data.get("edit_content", "")
48
+ edit_index = data.get("edit_index", 0)
49
+
50
+ if not edit_content:
51
+ return
52
+
53
+ # logger.debug(f"📦 接收内容片段 [index={edit_index}]: {edit_content[:1000]}...")
54
+
55
+ # 更新内容缓冲区
56
+ self._apply_edit_to_buffer(edit_index, edit_content)
57
+
58
+ # 尝试解析和处理工具调用
59
+ yield from self._process_tool_calls_from_buffer(is_stream)
60
+
61
+ def _apply_edit_to_buffer(self, edit_index: int, edit_content: str):
62
+ """
63
+ 在指定位置替换/插入内容更新内容缓冲区
64
+ """
65
+ edit_bytes = edit_content.encode('utf-8')
66
+ required_length = edit_index + len(edit_bytes)
67
+
68
+ # 扩展缓冲区到所需长度(如果需要)
69
+ if len(self.content_buffer) < edit_index:
70
+ # 如果edit_index超出当前缓冲区,用空字节填充
71
+ self.content_buffer.extend(b'\x00' * (edit_index - len(self.content_buffer)))
72
+
73
+ # 确保缓冲区足够长以容纳新内容
74
+ if len(self.content_buffer) < required_length:
75
+ self.content_buffer.extend(b'\x00' * (required_length - len(self.content_buffer)))
76
+
77
+ # 在指定位置替换内容(不是插入,而是覆盖)
78
+ end_index = edit_index + len(edit_bytes)
79
+ self.content_buffer[edit_index:end_index] = edit_bytes
80
+
81
+ # logger.debug(f"📝 缓冲区更新 [index={edit_index}, 长度={len(self.content_buffer)}]")
82
+
83
+ def _process_tool_calls_from_buffer(self, is_stream: bool) -> Generator[str, None, None]:
84
+ """
85
+ 从内容缓冲区中解析和处理工具调用
86
+ """
87
+ try:
88
+ # 解码内容并清理空字节
89
+ content_str = self.content_buffer.decode('utf-8', errors='ignore').replace('\x00', '')
90
+ yield from self._extract_and_process_tools(content_str, is_stream)
91
+ except Exception as e:
92
+ logger.debug(f"📦 内容解析暂时失败,等待更多数据: {e}")
93
+ # 不抛出异常,继续等待更多数据
94
+
95
+ def _extract_and_process_tools(self, content_str: str, is_stream: bool) -> Generator[str, None, None]:
96
+ """
97
+ 从内容字符串中提取和处理工具调用
98
+ """
99
+ # 查找所有 glm_block,包括不完整的
100
+ pattern = r'<glm_block\s*>(.*?)(?:</glm_block>|$)'
101
+ matches = re.findall(pattern, content_str, re.DOTALL)
102
+
103
+ for block_content in matches:
104
+ # 尝试解析每个块
105
+ yield from self._process_single_tool_block(block_content, is_stream)
106
+
107
+ def _process_single_tool_block(self, block_content: str, is_stream: bool) -> Generator[str, None, None]:
108
+ """
109
+ 处理单个工具块,支持增量解析
110
+ """
111
+ try:
112
+ # 尝试修复和解析完整的JSON
113
+ fixed_content = self._fix_json_structure(block_content)
114
+ tool_data = json.loads(fixed_content)
115
+ metadata = tool_data.get("data", {}).get("metadata", {})
116
+
117
+ tool_id = metadata.get("id", "")
118
+ tool_name = metadata.get("name", "")
119
+ arguments_raw = metadata.get("arguments", "{}")
120
+
121
+ if not tool_id or not tool_name:
122
+ return
123
+
124
+ logger.debug(f"🎯 解析完整工具块: {tool_name}(id={tool_id}), 参数: {arguments_raw}")
125
+
126
+ # 检查是否是新工具或更新的工具
127
+ yield from self._handle_tool_update(tool_id, tool_name, arguments_raw, is_stream)
128
+
129
+ except json.JSONDecodeError as e:
130
+ logger.debug(f"📦 JSON解析失败: {e}, 尝试部分解析")
131
+ # JSON 不完整,尝试部分解析
132
+ yield from self._handle_partial_tool_block(block_content, is_stream)
133
+ except Exception as e:
134
+ logger.debug(f"📦 工具块处理失败: {e}")
135
+
136
+ def _fix_json_structure(self, content: str) -> str:
137
+ """
138
+ 修复JSON结构中的常见问题
139
+ """
140
+ if not content:
141
+ return content
142
+
143
+ # 计算括号平衡
144
+ open_braces = content.count('{')
145
+ close_braces = content.count('}')
146
+
147
+ # 如果闭括号多于开括号,移除多余的闭括号
148
+ if close_braces > open_braces:
149
+ excess = close_braces - open_braces
150
+ fixed_content = content
151
+ for _ in range(excess):
152
+ # 从右侧移除多余的闭括号
153
+ last_brace_pos = fixed_content.rfind('}')
154
+ if last_brace_pos != -1:
155
+ fixed_content = fixed_content[:last_brace_pos] + fixed_content[last_brace_pos + 1:]
156
+ return fixed_content
157
+
158
+ return content
159
+
160
+ def _handle_tool_update(self, tool_id: str, tool_name: str, arguments_raw: str, is_stream: bool) -> Generator[str, None, None]:
161
+ """
162
+ 处理工具的创建或更新 - 更可靠的参数完整性检查
163
+ """
164
+ # 解析参数
165
+ try:
166
+ if isinstance(arguments_raw, str):
167
+ # 先处理转义和清理
168
+ cleaned_args = self._clean_arguments_string(arguments_raw)
169
+ arguments = json.loads(cleaned_args) if cleaned_args.strip() else {}
170
+ else:
171
+ arguments = arguments_raw
172
+ except json.JSONDecodeError:
173
+ logger.debug(f"📦 参数解析失败,暂不处理: {arguments_raw}")
174
+ # 参数解析失败时,不创建或更新工具,等待更完整的数据
175
+ return
176
+
177
+ # 检查参数是否看起来完整(基本的完整性验证)
178
+ is_args_complete = self._is_arguments_complete(arguments, arguments_raw)
179
+
180
+ # 检查是否是新工具
181
+ if tool_id not in self.active_tools:
182
+ logger.debug(f"🎯 发现新工具: {tool_name}(id={tool_id}), 参数完整性: {is_args_complete}")
183
+
184
+ self.active_tools[tool_id] = {
185
+ "id": tool_id,
186
+ "name": tool_name,
187
+ "arguments": arguments,
188
+ "arguments_raw": arguments_raw,
189
+ "status": "active",
190
+ "sent_start": False,
191
+ "last_sent_args": {}, # 跟踪上次发送的参数
192
+ "args_complete": is_args_complete,
193
+ "pending_send": True # 标记需要发送
194
+ }
195
+
196
+ # 只有在参数看起来完整时才发送工具开始信号
197
+ if is_stream and is_args_complete:
198
+ yield self._create_tool_start_chunk(tool_id, tool_name, arguments)
199
+ self.active_tools[tool_id]["sent_start"] = True
200
+ self.active_tools[tool_id]["last_sent_args"] = arguments.copy()
201
+ self.active_tools[tool_id]["pending_send"] = False
202
+ logger.debug(f"📤 发送完整工具开始: {tool_name}(id={tool_id})")
203
+
204
+ else:
205
+ # 更新现有工具
206
+ current_tool = self.active_tools[tool_id]
207
+
208
+ # 检查是否有实质性改进
209
+ if self._is_significant_improvement(current_tool["arguments"], arguments,
210
+ current_tool["arguments_raw"], arguments_raw):
211
+ logger.debug(f"🔄 工具参数有实质性改进: {tool_name}(id={tool_id})")
212
+
213
+ current_tool["arguments"] = arguments
214
+ current_tool["arguments_raw"] = arguments_raw
215
+ current_tool["args_complete"] = is_args_complete
216
+
217
+ # 如果之前没有发送过开始信号,且现在参数完整,发送开始信号
218
+ if is_stream and not current_tool["sent_start"] and is_args_complete:
219
+ yield self._create_tool_start_chunk(tool_id, tool_name, arguments)
220
+ current_tool["sent_start"] = True
221
+ current_tool["last_sent_args"] = arguments.copy()
222
+ current_tool["pending_send"] = False
223
+ logger.debug(f"📤 发送延迟的工具开始: {tool_name}(id={tool_id})")
224
+
225
+ # 如果已经发送过开始信号,且参数有显著改进,发送参数更新
226
+ elif is_stream and current_tool["sent_start"] and is_args_complete:
227
+ if self._should_send_argument_update(current_tool["last_sent_args"], arguments):
228
+ yield self._create_tool_arguments_chunk(tool_id, arguments)
229
+ current_tool["last_sent_args"] = arguments.copy()
230
+ logger.debug(f"📤 发送参数更新: {tool_name}(id={tool_id})")
231
+
232
+ def _is_arguments_complete(self, arguments: Dict[str, Any], arguments_raw: str) -> bool:
233
+ """
234
+ 检查参数��否看起来完整
235
+ """
236
+ if not arguments:
237
+ return False
238
+
239
+ # 检查原始字符串是否看起来完整
240
+ if not arguments_raw or not arguments_raw.strip():
241
+ return False
242
+
243
+ # 检查是否有明显的截断迹象
244
+ raw_stripped = arguments_raw.strip()
245
+
246
+ # 如果原始字符串不以}结尾,可能是截断的
247
+ if not raw_stripped.endswith('}') and not raw_stripped.endswith('"'):
248
+ return False
249
+
250
+ # 检查是否有不完整的URL(常见的截断情况)
251
+ for key, value in arguments.items():
252
+ if isinstance(value, str):
253
+ # 检查URL是否看起来完整
254
+ if 'http' in value.lower():
255
+ # 如果URL太短或以不完整的域名结尾,可能是截断的
256
+ if len(value) < 10 or value.endswith('.go') or value.endswith('.goo'):
257
+ return False
258
+
259
+ # 检查其他可能的截断迹象
260
+ if len(value) > 0 and value[-1] in ['.', '/', ':', '=']:
261
+ # 以这些字符结尾可能表示截断
262
+ return False
263
+
264
+ return True
265
+
266
+ def _is_significant_improvement(self, old_args: Dict[str, Any], new_args: Dict[str, Any],
267
+ old_raw: str, new_raw: str) -> bool:
268
+ """
269
+ 检查新参数是否比旧参数有显著改进
270
+ """
271
+ # 如果新参数为空,不是改进
272
+ if not new_args:
273
+ return False
274
+
275
+ if len(new_args) > len(old_args):
276
+ return True
277
+
278
+ # 检查值的改进
279
+ for key, new_value in new_args.items():
280
+ old_value = old_args.get(key, "")
281
+
282
+ if isinstance(new_value, str) and isinstance(old_value, str):
283
+ # 如果新值明显更长且更完整,是改进
284
+ if len(new_value) > len(old_value) + 5: # 至少长5个字符才算显著改进
285
+ return True
286
+
287
+ # 如果旧值看起来是截断的,新值更完整,是改进
288
+ if old_value.endswith(('.go', '.goo', '.com/', 'http')) and len(new_value) > len(old_value):
289
+ return True
290
+
291
+ # 检查原始字符串的改进
292
+ if len(new_raw) > len(old_raw) + 10: # 原始字符串显著增长
293
+ return True
294
+
295
+ return False
296
+
297
+ def _should_send_argument_update(self, last_sent: Dict[str, Any], new_args: Dict[str, Any]) -> bool:
298
+ """
299
+ 判断是否应该发送参数更新 - 更严格的标准
300
+ """
301
+ # 如果参数完全相同,不发送
302
+ if last_sent == new_args:
303
+ return False
304
+
305
+ # 如果新参数为空但之前有参数,不发送(避免倒退)
306
+ if not new_args and last_sent:
307
+ return False
308
+
309
+ # 如果新参数有更多键,发送更新
310
+ if len(new_args) > len(last_sent):
311
+ return True
312
+
313
+ # 检查是否有值变得显著更完整
314
+ for key, new_value in new_args.items():
315
+ last_value = last_sent.get(key, "")
316
+ if isinstance(new_value, str) and isinstance(last_value, str):
317
+ # 只有在值显著增长时才发送更新(避免微小变化)
318
+ if len(new_value) > len(last_value) + 5:
319
+ return True
320
+ elif new_value != last_value and new_value: # 确保新值不为空
321
+ return True
322
+
323
+ return False
324
+
325
+ def _handle_partial_tool_block(self, block_content: str, is_stream: bool) -> Generator[str, None, None]:
326
+ """
327
+ 处理不完整的工具块,尝试提取可用信息
328
+ """
329
+ try:
330
+ # 尝试提取工具ID和名称
331
+ id_match = re.search(r'"id":\s*"([^"]+)"', block_content)
332
+ name_match = re.search(r'"name":\s*"([^"]+)"', block_content)
333
+
334
+ if id_match and name_match:
335
+ tool_id = id_match.group(1)
336
+ tool_name = name_match.group(1)
337
+
338
+ # 尝试提取参数部分
339
+ args_match = re.search(r'"arguments":\s*"([^"]*)', block_content)
340
+ partial_args = args_match.group(1) if args_match else ""
341
+
342
+ logger.debug(f"📦 部分工具块: {tool_name}(id={tool_id}), 部分参数: {partial_args[:50]}")
343
+
344
+ # 如果是新工具,先创建记录
345
+ if tool_id not in self.active_tools:
346
+ # 尝试解析部分参数为字典
347
+ partial_args_dict = self._parse_partial_arguments(partial_args)
348
+
349
+ self.active_tools[tool_id] = {
350
+ "id": tool_id,
351
+ "name": tool_name,
352
+ "arguments": partial_args_dict,
353
+ "status": "partial",
354
+ "sent_start": False,
355
+ "last_sent_args": {},
356
+ "args_complete": False,
357
+ "partial_args": partial_args
358
+ }
359
+
360
+ if is_stream:
361
+ yield self._create_tool_start_chunk(tool_id, tool_name, partial_args_dict)
362
+ self.active_tools[tool_id]["sent_start"] = True
363
+ self.active_tools[tool_id]["last_sent_args"] = partial_args_dict.copy()
364
+ else:
365
+ # 更新部分参数
366
+ self.active_tools[tool_id]["partial_args"] = partial_args
367
+ # 尝试更新解析的参数
368
+ new_partial_dict = self._parse_partial_arguments(partial_args)
369
+ if new_partial_dict != self.active_tools[tool_id]["arguments"]:
370
+ self.active_tools[tool_id]["arguments"] = new_partial_dict
371
+
372
+ except Exception as e:
373
+ logger.debug(f"📦 部分块解析失败: {e}")
374
+
375
+ def _clean_arguments_string(self, arguments_raw: str) -> str:
376
+ """
377
+ 清理和标准化参数字符串,改进对不完整JSON的处理
378
+ """
379
+ if not arguments_raw:
380
+ return "{}"
381
+
382
+ # 移除首尾空白
383
+ cleaned = arguments_raw.strip()
384
+
385
+ # 处理特殊值
386
+ if cleaned.lower() == "null":
387
+ return "{}"
388
+
389
+ # 处理转义的JSON字符串
390
+ if cleaned.startswith('{\\"') and cleaned.endswith('\\"}'):
391
+ # 这是一个转义的JSON字符串,需要反转义
392
+ cleaned = cleaned.replace('\\"', '"')
393
+ elif cleaned.startswith('"{\\"') and cleaned.endswith('\\"}'):
394
+ # 双重转义的情况
395
+ cleaned = cleaned[1:-1].replace('\\"', '"')
396
+ elif cleaned.startswith('"') and cleaned.endswith('"'):
397
+ # 简单的引号包围,去除外层引号
398
+ cleaned = cleaned[1:-1]
399
+
400
+ # 处理不完整的JSON字符串
401
+ cleaned = self._fix_incomplete_json(cleaned)
402
+
403
+ # 标准化空格(移除JSON中的多余空格,但保留字符串值中的空格)
404
+ try:
405
+ # 先尝试解析,然后重新序列化以标准化格式
406
+ parsed = json.loads(cleaned)
407
+ if parsed is None:
408
+ return "{}"
409
+ cleaned = json.dumps(parsed, ensure_ascii=False, separators=(',', ':'))
410
+ except json.JSONDecodeError:
411
+ # 如果解析失败,只做基本的空格清理
412
+ logger.debug(f"📦 JSON标准化失败,保持原样: {cleaned[:50]}...")
413
+
414
+ return cleaned
415
+
416
+ def _fix_incomplete_json(self, json_str: str) -> str:
417
+ """
418
+ 修复不完整的JSON字符串
419
+ """
420
+ if not json_str:
421
+ return "{}"
422
+
423
+ # 确保以{开头
424
+ if not json_str.startswith('{'):
425
+ json_str = '{' + json_str
426
+
427
+ # 处理不完整的字符串值
428
+ if json_str.count('"') % 2 != 0:
429
+ # 奇数个引号,可能有未闭合的字符串
430
+ json_str += '"'
431
+
432
+ # 确保以}结尾
433
+ if not json_str.endswith('}'):
434
+ json_str += '}'
435
+
436
+ return json_str
437
+
438
+ def _parse_partial_arguments(self, arguments_raw: str) -> Dict[str, Any]:
439
+ """
440
+ 解析不完整的参数字符串,尽可能提取有效信息
441
+ """
442
+ if not arguments_raw or arguments_raw.strip() == "" or arguments_raw.strip().lower() == "null":
443
+ return {}
444
+
445
+ try:
446
+ # 先尝试清理字符串
447
+ cleaned = self._clean_arguments_string(arguments_raw)
448
+ result = json.loads(cleaned)
449
+ # 确保返回字典类型
450
+ return result if isinstance(result, dict) else {}
451
+ except json.JSONDecodeError:
452
+ pass
453
+
454
+ try:
455
+ # 尝试修复常见的JSON问题
456
+ fixed_args = arguments_raw.strip()
457
+
458
+ # 处理转义字符
459
+ if '\\' in fixed_args:
460
+ fixed_args = fixed_args.replace('\\"', '"')
461
+
462
+ # 如果不是以{开头,添加{
463
+ if not fixed_args.startswith('{'):
464
+ fixed_args = '{' + fixed_args
465
+
466
+ # 如果不是以}结尾,尝试添加}
467
+ if not fixed_args.endswith('}'):
468
+ # 计算未闭合的引号和括号
469
+ quote_count = fixed_args.count('"') - fixed_args.count('\\"')
470
+ if quote_count % 2 != 0:
471
+ fixed_args += '"'
472
+ fixed_args += '}'
473
+
474
+ return json.loads(fixed_args)
475
+ except json.JSONDecodeError:
476
+ # 尝试提取键值对
477
+ return self._extract_key_value_pairs(arguments_raw)
478
+ except Exception:
479
+ # 如果所有方法都失败,返回空字典
480
+ return {}
481
+
482
+ def _extract_key_value_pairs(self, text: str) -> Dict[str, Any]:
483
+ """
484
+ 从文本中提取键值对,作为最后的解析尝试
485
+ """
486
+ result = {}
487
+ try:
488
+ # 使用正则表达式提取简单的键值对
489
+ import re
490
+
491
+ # 匹配 "key": "value" 或 "key": value 格式
492
+ pattern = r'"([^"]+)":\s*"([^"]*)"'
493
+ matches = re.findall(pattern, text)
494
+
495
+ for key, value in matches:
496
+ result[key] = value
497
+
498
+ # 匹配数字值
499
+ pattern = r'"([^"]+)":\s*(\d+)'
500
+ matches = re.findall(pattern, text)
501
+
502
+ for key, value in matches:
503
+ try:
504
+ result[key] = int(value)
505
+ except ValueError:
506
+ result[key] = value
507
+
508
+ # 匹配布尔值
509
+ pattern = r'"([^"]+)":\s*(true|false)'
510
+ matches = re.findall(pattern, text)
511
+
512
+ for key, value in matches:
513
+ result[key] = value.lower() == 'true'
514
+
515
+ except Exception:
516
+ pass
517
+
518
+ return result
519
+
520
+ def _complete_active_tools(self, is_stream: bool) -> Generator[str, None, None]:
521
+ """
522
+ 完成所有活跃的工具调用 - 处理待发送的工具
523
+ """
524
+ tools_to_send = []
525
+
526
+ for tool_id, tool in self.active_tools.items():
527
+ # 如果工具还没有发送过且参数看起来完整,现在发送
528
+ if is_stream and tool.get("pending_send", False) and not tool.get("sent_start", False):
529
+ if tool.get("args_complete", False):
530
+ logger.debug(f"📤 完成时发送待发送工具: {tool['name']}(id={tool_id})")
531
+ yield self._create_tool_start_chunk(tool_id, tool["name"], tool["arguments"])
532
+ tool["sent_start"] = True
533
+ tool["pending_send"] = False
534
+ tools_to_send.append(tool)
535
+ else:
536
+ logger.debug(f"⚠️ 跳过不完整的工具: {tool['name']}(id={tool_id})")
537
+
538
+ tool["status"] = "completed"
539
+ self.completed_tools.append(tool)
540
+ logger.debug(f"✅ 完成工具调用: {tool['name']}(id={tool_id})")
541
+
542
+ self.active_tools.clear()
543
+
544
+ if is_stream and (self.completed_tools or tools_to_send):
545
+ # 发送工具完成信号
546
+ yield self._create_tool_finish_chunk()
547
+
548
+ def process_other_phase(self, data: Dict[str, Any], is_stream: bool = True) -> Generator[str, None, None]:
549
+ """
550
+ 处理other阶段 - 检测工具调用结束和状态更新
551
+ """
552
+ edit_content = data.get("edit_content", "")
553
+ edit_index = data.get("edit_index", 0)
554
+ usage = data.get("usage")
555
+
556
+ # 保存usage信息
557
+ if self.has_tool_call and usage:
558
+ self.tool_call_usage = usage
559
+ logger.debug(f"💾 保存工具调用usage: {usage}")
560
+
561
+ # 如果有edit_content,继续更新内容缓冲区
562
+ if edit_content:
563
+ self._apply_edit_to_buffer(edit_index, edit_content)
564
+ # 继续处理可能的工具调用更新
565
+ yield from self._process_tool_calls_from_buffer(is_stream)
566
+
567
+ # 检测工具调用结束的多种标记
568
+ if self.has_tool_call and self._is_tool_call_finished(edit_content):
569
+ logger.debug("🏁 检测到工具调用结束")
570
+
571
+ # 完成所有活跃的工具
572
+ yield from self._complete_active_tools(is_stream)
573
+
574
+ if is_stream:
575
+ logger.info("🏁 发送工具调用完成信号")
576
+ yield "data: [DONE]"
577
+
578
+ # 重置工具调用状态
579
+ self.has_tool_call = False
580
+
581
+ def _is_tool_call_finished(self, edit_content: str) -> bool:
582
+ """
583
+ 检测工具调用是否结束的多种标记
584
+ """
585
+ if not edit_content:
586
+ return False
587
+
588
+ # 检测各种结束标记
589
+ end_markers = [
590
+ "null,", # 原有的结束标记
591
+ '"status": "completed"', # 状态完成标记
592
+ '"is_error": false', # 错误状态标记
593
+ ]
594
+
595
+ for marker in end_markers:
596
+ if marker in edit_content:
597
+ logger.debug(f"🔍 检测到结束标记: {marker}")
598
+ return True
599
+
600
+ # 检查是否所有工具都有完整的结构
601
+ if self.active_tools and '"status": "completed"' in self.content_buffer:
602
+ return True
603
+
604
+ return False
605
+
606
+ def _reset_all_state(self):
607
+ """重置所有状态"""
608
+ self.has_tool_call = False
609
+ self.tool_call_usage = None
610
+ self.content_index = 0
611
+ self.content_buffer = bytearray()
612
+ self.last_edit_index = 0
613
+ self.active_tools.clear()
614
+ self.completed_tools.clear()
615
+ self.tool_blocks_cache.clear()
616
+
617
+ def _create_tool_start_chunk(self, tool_id: str, tool_name: str, initial_args: Dict[str, Any] = None) -> str:
618
+ """创建工具调用开始的chunk,支持初始参数"""
619
+ # 使用提供的初始参数,如果没有则使用空字典
620
+ args_dict = initial_args or {}
621
+ args_str = json.dumps(args_dict, ensure_ascii=False)
622
+
623
+ chunk = {
624
+ "choices": [
625
+ {
626
+ "delta": {
627
+ "role": "assistant",
628
+ "content": None,
629
+ "tool_calls": [
630
+ {
631
+ "id": tool_id,
632
+ "type": "function",
633
+ "function": {"name": tool_name, "arguments": args_str},
634
+ }
635
+ ],
636
+ },
637
+ "finish_reason": None,
638
+ "index": self.content_index,
639
+ "logprobs": None,
640
+ }
641
+ ],
642
+ "created": int(time.time()),
643
+ "id": self.chat_id,
644
+ "model": self.model,
645
+ "object": "chat.completion.chunk",
646
+ "system_fingerprint": "fp_zai_001",
647
+ }
648
+ return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
649
+
650
+ def _create_tool_arguments_chunk(self, tool_id: str, arguments: Dict) -> str:
651
+ """创建工具参数的chunk - 只包含参数更新,不包含函数名"""
652
+ chunk = {
653
+ "choices": [
654
+ {
655
+ "delta": {
656
+ "tool_calls": [
657
+ {
658
+ "id": tool_id,
659
+ "function": {"arguments": json.dumps(arguments, ensure_ascii=False)},
660
+ }
661
+ ],
662
+ },
663
+ "finish_reason": None,
664
+ "index": self.content_index,
665
+ "logprobs": None,
666
+ }
667
+ ],
668
+ "created": int(time.time()),
669
+ "id": self.chat_id,
670
+ "model": self.model,
671
+ "object": "chat.completion.chunk",
672
+ "system_fingerprint": "fp_zai_001",
673
+ }
674
+ return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
675
+
676
+ def _create_tool_finish_chunk(self) -> str:
677
+ """创建工具调用完成的chunk"""
678
+ chunk = {
679
+ "choices": [
680
+ {
681
+ "delta": {"role": "assistant", "content": None, "tool_calls": []},
682
+ "finish_reason": "tool_calls",
683
+ "index": 0,
684
+ "logprobs": None,
685
+ }
686
+ ],
687
+ "created": int(time.time()),
688
+ "id": self.chat_id,
689
+ "usage": self.tool_call_usage or None,
690
+ "model": self.model,
691
+ "object": "chat.completion.chunk",
692
+ "system_fingerprint": "fp_zai_001",
693
+ }
694
+ return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
app/utils/token_pool.py ADDED
@@ -0,0 +1,454 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ Token池管理器
6
+ 实现AUTH_TOKEN的轮询机制,提供负载均衡和容错功能
7
+ """
8
+
9
+ import asyncio
10
+ import time
11
+ from typing import Dict, List, Optional, Tuple
12
+ from dataclasses import dataclass, field
13
+ from threading import Lock
14
+ import httpx
15
+ import requests
16
+
17
+ from app.utils.logger import logger
18
+
19
+
20
+ @dataclass
21
+ class TokenStatus:
22
+ """Token状态信息"""
23
+ token: str
24
+ is_available: bool = True
25
+ failure_count: int = 0
26
+ last_failure_time: float = 0.0
27
+ last_success_time: float = 0.0
28
+ total_requests: int = 0
29
+ successful_requests: int = 0
30
+ token_type: str = "unknown" # "user", "guest", "unknown"
31
+
32
+ @property
33
+ def success_rate(self) -> float:
34
+ """成功率"""
35
+ if self.total_requests == 0:
36
+ return 1.0
37
+ return self.successful_requests / self.total_requests
38
+
39
+ @property
40
+ def is_healthy(self) -> bool:
41
+ """
42
+ 是否健康
43
+
44
+ 健康的定义:
45
+ 1. 必须是认证用户token (token_type = "user")
46
+ 2. 当前可用 (is_available = True)
47
+ 3. 成功率 >= 50% 或者总请求数 <= 3(新token容错)
48
+
49
+ 注意:guest token不应该在AUTH_TOKENS中
50
+ """
51
+ # guest token永远不健康
52
+ if self.token_type == "guest":
53
+ return False
54
+
55
+ # 未知类型token不健康
56
+ if self.token_type != "user":
57
+ return False
58
+
59
+ # 不可用的token不健康
60
+ if not self.is_available:
61
+ return False
62
+
63
+ # 对于认证用户token,基于成功率判断
64
+ # 新token或请求数很少时,给予容错
65
+ if self.total_requests <= 3:
66
+ return self.failure_count == 0
67
+
68
+ # 基于成功率判断健康状态
69
+ return self.success_rate >= 0.5
70
+
71
+
72
+ class TokenPool:
73
+ """Token池管理器"""
74
+
75
+ def __init__(self, tokens: List[str], failure_threshold: int = 3, recovery_timeout: int = 1800):
76
+ """
77
+ 初始化Token池
78
+
79
+ Args:
80
+ tokens: token列表
81
+ failure_threshold: 失败阈值,超过此次数将标记为不可用
82
+ recovery_timeout: 恢复超时时间(秒),失败token在此时间后重新尝试
83
+ """
84
+ self.failure_threshold = failure_threshold
85
+ self.recovery_timeout = recovery_timeout
86
+ self._lock = Lock()
87
+ self._current_index = 0
88
+
89
+ # 初始化token状态
90
+ self.token_statuses: Dict[str, TokenStatus] = {}
91
+ original_count = len(tokens)
92
+ unique_tokens = []
93
+
94
+ # 去重处理
95
+ for token in tokens:
96
+ if token and token not in self.token_statuses: # 过滤空token和重复token
97
+ self.token_statuses[token] = TokenStatus(token=token)
98
+ unique_tokens.append(token)
99
+
100
+ duplicate_count = original_count - len(unique_tokens)
101
+ if duplicate_count > 0:
102
+ logger.warning(f"⚠️ 检测到 {duplicate_count} 个重复token,已自动去重")
103
+
104
+ if not self.token_statuses:
105
+ logger.warning("⚠️ Token池为空,将依赖匿名模式")
106
+ else:
107
+ logger.info(f"🔧 初始化Token池,共 {len(self.token_statuses)} 个token")
108
+
109
+ def get_next_token(self) -> Optional[str]:
110
+ """
111
+ 获取下一个可用的token(轮询算法)
112
+
113
+ Returns:
114
+ 可用的token,如果没有可用token则返回None
115
+ """
116
+ with self._lock:
117
+ if not self.token_statuses:
118
+ return None
119
+
120
+ available_tokens = self._get_available_tokens()
121
+ if not available_tokens:
122
+ # 尝试恢复过期的失败token
123
+ self._try_recover_failed_tokens()
124
+ available_tokens = self._get_available_tokens()
125
+
126
+ if not available_tokens:
127
+ logger.warning("⚠️ 没有可用的token")
128
+ return None
129
+
130
+ # 轮询选择token
131
+ token = available_tokens[self._current_index % len(available_tokens)]
132
+ self._current_index = (self._current_index + 1) % len(available_tokens)
133
+
134
+ return token
135
+
136
+ def _get_available_tokens(self) -> List[str]:
137
+ """
138
+ 获取当前可用的认证用户token列表
139
+
140
+ 只返回满足以下条件的token:
141
+ 1. is_available = True (可用状态)
142
+ 2. token_type = "user" (认证用户token)
143
+
144
+ 这确保轮询机制只会选择有效的认证用户token,跳过匿名用户token
145
+ """
146
+ available_user_tokens = [
147
+ status.token for status in self.token_statuses.values()
148
+ if status.is_available and status.token_type == "user"
149
+ ]
150
+
151
+ # 如果没有可用的认证用户token
152
+ if not available_user_tokens and self.token_statuses:
153
+ guest_tokens = [
154
+ status.token for status in self.token_statuses.values()
155
+ if status.token_type == "guest"
156
+ ]
157
+ if guest_tokens:
158
+ logger.warning(f"⚠️ 检测到 {len(guest_tokens)} 个匿名用户token,轮询机制将跳过这些token")
159
+
160
+ return available_user_tokens
161
+
162
+ def _try_recover_failed_tokens(self):
163
+ """尝试恢复失败的token"""
164
+ current_time = time.time()
165
+ recovered_count = 0
166
+
167
+ for status in self.token_statuses.values():
168
+ if (not status.is_available and
169
+ current_time - status.last_failure_time > self.recovery_timeout):
170
+ status.is_available = True
171
+ status.failure_count = 0
172
+ recovered_count += 1
173
+ logger.info(f"🔄 恢复失败token: {status.token[:20]}...")
174
+
175
+ if recovered_count > 0:
176
+ logger.info(f"✅ 恢复了 {recovered_count} 个失败的token")
177
+
178
+ def mark_token_success(self, token: str):
179
+ """标记token使用成功"""
180
+ with self._lock:
181
+ if token in self.token_statuses:
182
+ status = self.token_statuses[token]
183
+ status.total_requests += 1
184
+ status.successful_requests += 1
185
+ status.last_success_time = time.time()
186
+ status.failure_count = 0 # 重置失败计数
187
+
188
+ if not status.is_available:
189
+ status.is_available = True
190
+ logger.info(f"✅ Token恢复可用: {token[:20]}...")
191
+
192
+ def mark_token_failure(self, token: str, error: Exception = None):
193
+ """标记token使用失败"""
194
+ with self._lock:
195
+ if token in self.token_statuses:
196
+ status = self.token_statuses[token]
197
+ status.total_requests += 1
198
+ status.failure_count += 1
199
+ status.last_failure_time = time.time()
200
+
201
+ if status.failure_count >= self.failure_threshold:
202
+ status.is_available = False
203
+ logger.warning(f"🚫 Token已禁用: {token[:20]}... (失败 {status.failure_count} 次)")
204
+
205
+ def get_pool_status(self) -> Dict:
206
+ """获取token池状态信息"""
207
+ with self._lock:
208
+ available_count = len(self._get_available_tokens())
209
+ total_count = len(self.token_statuses)
210
+
211
+ # 统计健康token数量
212
+ healthy_count = sum(1 for status in self.token_statuses.values() if status.is_healthy)
213
+
214
+ status_info = {
215
+ "total_tokens": total_count,
216
+ "available_tokens": available_count,
217
+ "unavailable_tokens": total_count - available_count,
218
+ "healthy_tokens": healthy_count,
219
+ "unhealthy_tokens": total_count - healthy_count,
220
+ "current_index": self._current_index,
221
+ "tokens": []
222
+ }
223
+
224
+ for token, status in self.token_statuses.items():
225
+ status_info["tokens"].append({
226
+ "token": f"{token[:10]}...{token[-10:]}",
227
+ "token_type": status.token_type,
228
+ "is_available": status.is_available,
229
+ "failure_count": status.failure_count,
230
+ "success_count": status.successful_requests,
231
+ "success_rate": f"{status.success_rate:.2%}",
232
+ "total_requests": status.total_requests,
233
+ "is_healthy": status.is_healthy,
234
+ "last_failure_time": status.last_failure_time,
235
+ "last_success_time": status.last_success_time
236
+ })
237
+
238
+ return status_info
239
+
240
+ def update_tokens(self, new_tokens: List[str]):
241
+ """动态更新token列表"""
242
+ with self._lock:
243
+ # 保留现有token的状态信息
244
+ old_statuses = self.token_statuses.copy()
245
+ self.token_statuses.clear()
246
+
247
+ original_count = len(new_tokens)
248
+ unique_tokens = []
249
+
250
+ # 去重并添加新token,保留已存在token的状态
251
+ for token in new_tokens:
252
+ if token and token not in self.token_statuses: # 过滤空token和重复token
253
+ if token in old_statuses:
254
+ self.token_statuses[token] = old_statuses[token]
255
+ else:
256
+ self.token_statuses[token] = TokenStatus(token=token)
257
+ unique_tokens.append(token)
258
+
259
+ # 记录去重信息
260
+ duplicate_count = original_count - len(unique_tokens)
261
+ if duplicate_count > 0:
262
+ logger.warning(f"⚠️ 更新时检测到 {duplicate_count} 个重复token,已自动去重")
263
+
264
+ # 重置索引
265
+ self._current_index = 0
266
+
267
+ logger.info(f"🔄 更新Token池,共 {len(self.token_statuses)} 个token")
268
+
269
+ async def health_check_token(self, token: str, auth_url: str = "https://chat.z.ai/api/v1/auths/") -> bool:
270
+ """
271
+ 异步健康检查单个token
272
+
273
+ 使用Z.AI认证API验证token的有效性,通过检查响应内容判断token是否有效
274
+
275
+ Args:
276
+ token: 要检查的token
277
+ auth_url: 认证URL
278
+
279
+ Returns:
280
+ token是否健康
281
+ """
282
+ try:
283
+ # 构建完整的请求头,模拟真实浏览器请求
284
+ headers = {
285
+ "Accept": "*/*",
286
+ "Accept-Language": "zh-CN,zh;q=0.9",
287
+ "Authorization": f"Bearer {token}",
288
+ "Connection": "keep-alive",
289
+ "Content-Type": "application/json",
290
+ "DNT": "1",
291
+ "Referer": "https://chat.z.ai/",
292
+ "Sec-Fetch-Dest": "empty",
293
+ "Sec-Fetch-Mode": "cors",
294
+ "Sec-Fetch-Site": "same-origin",
295
+ "User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/140.0.0.0 Safari/537.36",
296
+ "sec-ch-ua": '"Chromium";v="140", "Not=A?Brand";v="24", "Google Chrome";v="140"',
297
+ "sec-ch-ua-mobile": "?0",
298
+ "sec-ch-ua-platform": "Windows"
299
+ }
300
+
301
+ async with httpx.AsyncClient(timeout=15.0) as client:
302
+ response = await client.get(auth_url, headers=headers)
303
+
304
+ # 验证token有效性并获取类型
305
+ token_type, is_healthy = self._validate_token_response(response)
306
+
307
+ # 更新token类型
308
+ if token in self.token_statuses:
309
+ self.token_statuses[token].token_type = token_type
310
+
311
+ if is_healthy:
312
+ self.mark_token_success(token)
313
+ else:
314
+ # 简化错误信息,只记录关键错误类型
315
+ if token_type == "guest":
316
+ error_msg = "匿名用户token"
317
+ elif response.status_code != 200:
318
+ error_msg = f"HTTP {response.status_code}"
319
+ else:
320
+ error_msg = "认证失败"
321
+
322
+ self.mark_token_failure(token, Exception(error_msg))
323
+
324
+ return is_healthy
325
+
326
+ except (httpx.TimeoutException, httpx.ConnectError, Exception) as e:
327
+ self.mark_token_failure(token, e)
328
+ return False
329
+
330
+ def _validate_token_response(self, response: httpx.Response) -> bool:
331
+ """
332
+ 基于Z.AI API响应中的role字段验证token类型
333
+
334
+ 验证规则:
335
+ - role: "user" = 认证用户token(有效,可用于AUTH_TOKENS)
336
+ - role: "guest" = 匿名用户token(无效,不应在AUTH_TOKENS中)
337
+ - 无role字段或其他值 = 无效token
338
+
339
+ Args:
340
+ response: HTTP响应对象
341
+
342
+ Returns:
343
+ token是否为有效的认证用户token
344
+ """
345
+ # 首先检查HTTP状态码
346
+ if response.status_code != 200:
347
+ return ("unknown", False)
348
+
349
+ try:
350
+ # 尝试解析JSON响应
351
+ response_data = response.json()
352
+
353
+ if not isinstance(response_data, dict):
354
+ return ("unknown", False)
355
+
356
+ # 检查是否包含错误信息
357
+ if "error" in response_data:
358
+ return ("unknown", False)
359
+
360
+ if "message" in response_data and "error" in response_data.get("message", "").lower():
361
+ return ("unknown", False)
362
+
363
+ # 核心验证:检查role字段
364
+ role = response_data.get("role")
365
+
366
+ if role == "user":
367
+ return ("user", True)
368
+ elif role == "guest":
369
+
370
+ if not hasattr(self, '_guest_token_warned'):
371
+ logger.warning("⚠️ 检测到匿名用户token,建议仅在AUTH_TOKENS中配置认证用户token")
372
+ self._guest_token_warned = True
373
+ return ("guest", False)
374
+ else:
375
+ return ("unknown", False)
376
+
377
+ except (ValueError, Exception):
378
+ return ("unknown", False)
379
+
380
+ async def health_check_all(self, auth_url: str = "https://chat.z.ai/api/v1/auths/"):
381
+ """异步健康检查所有token"""
382
+ if not self.token_statuses:
383
+ logger.warning("⚠️ Token池为空,跳过健康检查")
384
+ return
385
+
386
+ total_tokens = len(self.token_statuses)
387
+ logger.info(f"🔍 开始Token池健康检查... (共 {total_tokens} 个token)")
388
+
389
+ # 并发执行所有token的健康检查
390
+ tasks = []
391
+ token_list = list(self.token_statuses.keys())
392
+
393
+ for token in token_list:
394
+ task = self.health_check_token(token, auth_url)
395
+ tasks.append(task)
396
+
397
+ # 执行并收集结果
398
+ results = await asyncio.gather(*tasks, return_exceptions=True)
399
+
400
+ # 统计结果
401
+ healthy_count = 0
402
+ failed_count = 0
403
+ exception_count = 0
404
+
405
+ for i, result in enumerate(results):
406
+ if result is True:
407
+ healthy_count += 1
408
+ elif result is False:
409
+ failed_count += 1
410
+ else:
411
+ # 异常情况
412
+ exception_count += 1
413
+ token = token_list[i]
414
+ logger.error(f"💥 Token {token[:20]}... 健康检查异常: {result}")
415
+
416
+ health_rate = (healthy_count / total_tokens) * 100 if total_tokens > 0 else 0
417
+
418
+ if healthy_count == 0 and total_tokens > 0:
419
+ logger.warning(f"⚠️ 健康检查完成: 0/{total_tokens} 个token健康 - 请检查token配置")
420
+ elif failed_count > 0:
421
+ logger.warning(f"⚠️ 健康检查完成: {healthy_count}/{total_tokens} 个token健康 ({health_rate:.1f}%)")
422
+ else:
423
+ logger.info(f"✅ 健康检查完成: {healthy_count}/{total_tokens} 个token健康")
424
+
425
+ if exception_count > 0:
426
+ logger.error(f"💥 {exception_count} 个token检查异常")
427
+
428
+
429
+ # 全局token池实例
430
+ _token_pool: Optional[TokenPool] = None
431
+ _pool_lock = Lock()
432
+
433
+
434
+ def get_token_pool() -> Optional[TokenPool]:
435
+ """获取全局token池实例"""
436
+ return _token_pool
437
+
438
+
439
+ def initialize_token_pool(tokens: List[str], failure_threshold: int = 3, recovery_timeout: int = 1800) -> TokenPool:
440
+ """初始化全局token池"""
441
+ global _token_pool
442
+ with _pool_lock:
443
+ _token_pool = TokenPool(tokens, failure_threshold, recovery_timeout)
444
+ return _token_pool
445
+
446
+
447
+ def update_token_pool(tokens: List[str]):
448
+ """更新全局token池"""
449
+ global _token_pool
450
+ with _pool_lock:
451
+ if _token_pool:
452
+ _token_pool.update_tokens(tokens)
453
+ else:
454
+ _token_pool = TokenPool(tokens)
app/utils/tools.py DELETED
@@ -1,325 +0,0 @@
1
- """
2
- Tool processing utilities
3
- """
4
-
5
- import json
6
- import re
7
- import time
8
- from typing import Dict, List, Optional, Any
9
-
10
- from app.core.config import settings
11
-
12
-
13
- def content_to_string(content: Any) -> str:
14
- """Convert content from various formats to string (following app.py pattern)"""
15
- if isinstance(content, str):
16
- return content
17
- if isinstance(content, list):
18
- parts = []
19
- for p in content:
20
- if isinstance(p, dict) and p.get("type") == "text":
21
- parts.append(p.get("text", ""))
22
- elif isinstance(p, str):
23
- parts.append(p)
24
- return " ".join(parts)
25
- return ""
26
-
27
-
28
- def generate_tool_prompt(tools: List[Dict[str, Any]]) -> str:
29
- """Generate tool injection prompt with enhanced formatting"""
30
- if not tools:
31
- return ""
32
-
33
- tool_definitions = []
34
- for tool in tools:
35
- if tool.get("type") != "function":
36
- continue
37
-
38
- function_spec = tool.get("function", {}) or {}
39
- function_name = function_spec.get("name", "unknown")
40
- function_description = function_spec.get("description", "")
41
- parameters = function_spec.get("parameters", {}) or {}
42
-
43
- # Create structured tool definition
44
- tool_info = [f"## {function_name}", f"**Purpose**: {function_description}"]
45
-
46
- # Add parameter details
47
- parameter_properties = parameters.get("properties", {}) or {}
48
- required_parameters = set(parameters.get("required", []) or [])
49
-
50
- if parameter_properties:
51
- tool_info.append("**Parameters**:")
52
- for param_name, param_details in parameter_properties.items():
53
- param_type = (param_details or {}).get("type", "any")
54
- param_desc = (param_details or {}).get("description", "")
55
- requirement_flag = "**Required**" if param_name in required_parameters else "*Optional*"
56
- tool_info.append(f"- `{param_name}` ({param_type}) - {requirement_flag}: {param_desc}")
57
-
58
- tool_definitions.append("\n".join(tool_info))
59
-
60
- if not tool_definitions:
61
- return ""
62
-
63
- # Build comprehensive tool prompt
64
- prompt_template = (
65
- "\n\n# AVAILABLE FUNCTIONS\n" + "\n\n---\n".join(tool_definitions) + "\n\n# USAGE INSTRUCTIONS\n"
66
- "When you need to execute a function, respond ONLY with a JSON object containing tool_calls:\n"
67
- "```json\n"
68
- "{\n"
69
- ' "tool_calls": [\n'
70
- " {\n"
71
- ' "id": "call_xxx",\n'
72
- ' "type": "function",\n'
73
- ' "function": {\n'
74
- ' "name": "function_name",\n'
75
- ' "arguments": "{\\"param1\\": \\"value1\\"}"\n'
76
- " }\n"
77
- " }\n"
78
- " ]\n"
79
- "}\n"
80
- "```\n"
81
- "Important: No explanatory text before or after the JSON. The 'arguments' field must be a JSON string, not an object.\n"
82
- )
83
-
84
- return prompt_template
85
-
86
-
87
- def process_messages_with_tools(
88
- messages: List[Dict[str, Any]], tools: Optional[List[Dict[str, Any]]] = None, tool_choice: Optional[Any] = None
89
- ) -> List[Dict[str, Any]]:
90
- """Process messages and inject tool prompts"""
91
- processed: List[Dict[str, Any]] = []
92
-
93
- if tools and settings.TOOL_SUPPORT and (tool_choice != "none"):
94
- tools_prompt = generate_tool_prompt(tools)
95
- has_system = any(m.get("role") == "system" for m in messages)
96
-
97
- if has_system:
98
- for m in messages:
99
- if m.get("role") == "system":
100
- mm = dict(m)
101
- content = content_to_string(mm.get("content", ""))
102
- mm["content"] = content + tools_prompt
103
- processed.append(mm)
104
- else:
105
- processed.append(m)
106
- else:
107
- processed = [{"role": "system", "content": "你是一个有用的助手。" + tools_prompt}] + messages
108
-
109
- # Add tool choice hints
110
- if tool_choice in ("required", "auto"):
111
- if processed and processed[-1].get("role") == "user":
112
- last = dict(processed[-1])
113
- content = content_to_string(last.get("content", ""))
114
- last["content"] = content + "\n\n请根据需要使用提供的工具函数。"
115
- processed[-1] = last
116
- elif isinstance(tool_choice, dict) and tool_choice.get("type") == "function":
117
- fname = (tool_choice.get("function") or {}).get("name")
118
- if fname and processed and processed[-1].get("role") == "user":
119
- last = dict(processed[-1])
120
- content = content_to_string(last.get("content", ""))
121
- last["content"] = content + f"\n\n请使用 {fname} 函数来处理这个请求。"
122
- processed[-1] = last
123
- else:
124
- processed = list(messages)
125
-
126
- # Handle tool/function messages
127
- final_msgs: List[Dict[str, Any]] = []
128
- for m in processed:
129
- role = m.get("role")
130
- if role in ("tool", "function"):
131
- tool_name = m.get("name", "unknown")
132
- tool_content = content_to_string(m.get("content", ""))
133
- if isinstance(tool_content, dict):
134
- tool_content = json.dumps(tool_content, ensure_ascii=False)
135
-
136
- # 确保内容不为空且不包含 None
137
- content = f"工具 {tool_name} 返回结果:\n```json\n{tool_content}\n```"
138
- if not content.strip():
139
- content = f"工具 {tool_name} 执行完成"
140
-
141
- final_msgs.append(
142
- {
143
- "role": "assistant",
144
- "content": content,
145
- }
146
- )
147
- else:
148
- # For regular messages, ensure content is string format
149
- final_msg = dict(m)
150
- content = content_to_string(final_msg.get("content", ""))
151
- final_msg["content"] = content
152
- final_msgs.append(final_msg)
153
-
154
- return final_msgs
155
-
156
-
157
- # Tool Extraction Patterns
158
- TOOL_CALL_FENCE_PATTERN = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL)
159
- # 注意:TOOL_CALL_INLINE_PATTERN 已被移除,因为它会导致过度匹配
160
- # 现在在 remove_tool_json_content 函数中使用基于括号平衡的方法
161
- FUNCTION_CALL_PATTERN = re.compile(r"调用函数\s*[::]\s*([\w\-\.]+)\s*(?:参数|arguments)[::]\s*(\{.*?\})", re.DOTALL)
162
-
163
-
164
- def extract_tool_invocations(text: str) -> Optional[List[Dict[str, Any]]]:
165
- """Extract tool invocations from response text"""
166
- if not text:
167
- return None
168
-
169
- # Limit scan size for performance
170
- scannable_text = text[: settings.SCAN_LIMIT]
171
-
172
- # Attempt 1: Extract from JSON code blocks
173
- json_blocks = TOOL_CALL_FENCE_PATTERN.findall(scannable_text)
174
- for json_block in json_blocks:
175
- try:
176
- parsed_data = json.loads(json_block)
177
- tool_calls = parsed_data.get("tool_calls")
178
- if tool_calls and isinstance(tool_calls, list):
179
- # Ensure arguments field is a string
180
- for tc in tool_calls:
181
- if "function" in tc:
182
- func = tc["function"]
183
- if "arguments" in func:
184
- if isinstance(func["arguments"], dict):
185
- # Convert dict to JSON string
186
- func["arguments"] = json.dumps(func["arguments"], ensure_ascii=False)
187
- elif not isinstance(func["arguments"], str):
188
- func["arguments"] = json.dumps(func["arguments"], ensure_ascii=False)
189
- return tool_calls
190
- except (json.JSONDecodeError, AttributeError):
191
- continue
192
-
193
- # Attempt 2: Extract inline JSON objects using bracket balance method
194
- # 查找包含 "tool_calls" 的 JSON 对象
195
- i = 0
196
- while i < len(scannable_text):
197
- if scannable_text[i] == '{':
198
- # 尝试找到匹配的右括号
199
- brace_count = 1
200
- j = i + 1
201
- in_string = False
202
- escape_next = False
203
-
204
- while j < len(scannable_text) and brace_count > 0:
205
- if escape_next:
206
- escape_next = False
207
- elif scannable_text[j] == '\\':
208
- escape_next = True
209
- elif scannable_text[j] == '"' and not escape_next:
210
- in_string = not in_string
211
- elif not in_string:
212
- if scannable_text[j] == '{':
213
- brace_count += 1
214
- elif scannable_text[j] == '}':
215
- brace_count -= 1
216
- j += 1
217
-
218
- if brace_count == 0:
219
- # 找到了完整的 JSON 对象
220
- json_str = scannable_text[i:j]
221
- try:
222
- parsed_data = json.loads(json_str)
223
- tool_calls = parsed_data.get("tool_calls")
224
- if tool_calls and isinstance(tool_calls, list):
225
- # Ensure arguments field is a string
226
- for tc in tool_calls:
227
- if "function" in tc:
228
- func = tc["function"]
229
- if "arguments" in func:
230
- if isinstance(func["arguments"], dict):
231
- # Convert dict to JSON string
232
- func["arguments"] = json.dumps(func["arguments"], ensure_ascii=False)
233
- elif not isinstance(func["arguments"], str):
234
- func["arguments"] = json.dumps(func["arguments"], ensure_ascii=False)
235
- return tool_calls
236
- except (json.JSONDecodeError, AttributeError):
237
- pass
238
-
239
- i += 1
240
- else:
241
- i += 1
242
-
243
- # Attempt 3: Parse natural language function calls
244
- natural_lang_match = FUNCTION_CALL_PATTERN.search(scannable_text)
245
- if natural_lang_match:
246
- function_name = natural_lang_match.group(1).strip()
247
- arguments_str = natural_lang_match.group(2).strip()
248
- try:
249
- # Validate JSON format
250
- json.loads(arguments_str)
251
- return [
252
- {
253
- "id": f"call_{int(time.time() * 1000000)}",
254
- "type": "function",
255
- "function": {"name": function_name, "arguments": arguments_str},
256
- }
257
- ]
258
- except json.JSONDecodeError:
259
- return None
260
-
261
- return None
262
-
263
-
264
- def remove_tool_json_content(text: str) -> str:
265
- """Remove tool JSON content from response text - using bracket balance method"""
266
-
267
- def remove_tool_call_block(match: re.Match) -> str:
268
- json_content = match.group(1)
269
- try:
270
- parsed_data = json.loads(json_content)
271
- if "tool_calls" in parsed_data:
272
- return ""
273
- except (json.JSONDecodeError, AttributeError):
274
- pass
275
- return match.group(0)
276
-
277
- # Step 1: Remove fenced tool JSON blocks
278
- cleaned_text = TOOL_CALL_FENCE_PATTERN.sub(remove_tool_call_block, text)
279
-
280
- # Step 2: Remove inline tool JSON - 使用基于括号平衡的智能方法
281
- # 查找所有可能的 JSON 对象并精确删除包含 tool_calls 的对象
282
- result = []
283
- i = 0
284
- while i < len(cleaned_text):
285
- if cleaned_text[i] == '{':
286
- # 尝试找到匹配的右括号
287
- brace_count = 1
288
- j = i + 1
289
- in_string = False
290
- escape_next = False
291
-
292
- while j < len(cleaned_text) and brace_count > 0:
293
- if escape_next:
294
- escape_next = False
295
- elif cleaned_text[j] == '\\':
296
- escape_next = True
297
- elif cleaned_text[j] == '"' and not escape_next:
298
- in_string = not in_string
299
- elif not in_string:
300
- if cleaned_text[j] == '{':
301
- brace_count += 1
302
- elif cleaned_text[j] == '}':
303
- brace_count -= 1
304
- j += 1
305
-
306
- if brace_count == 0:
307
- # 找到了完整的 JSON 对象
308
- json_str = cleaned_text[i:j]
309
- try:
310
- parsed = json.loads(json_str)
311
- if "tool_calls" in parsed:
312
- # 这是一个工具调用,跳过它
313
- i = j
314
- continue
315
- except:
316
- pass
317
-
318
- # 不是工具调用或无法解析,保留这个字符
319
- result.append(cleaned_text[i])
320
- i += 1
321
- else:
322
- result.append(cleaned_text[i])
323
- i += 1
324
-
325
- return ''.join(result).strip()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
deploy/docker-compose.yml CHANGED
@@ -15,8 +15,6 @@ services:
15
  - SKIP_AUTH_TOKEN=false
16
  # Server Configurations
17
  - DEBUG_LOGGING=true
18
- # Feature Configuration
19
- - THINKING_PROCESSING=think
20
  - ANONYMOUS_MODE=true
21
  - TOOL_SUPPORT=true
22
  - SCAN_LIMIT=200000
 
15
  - SKIP_AUTH_TOKEN=false
16
  # Server Configurations
17
  - DEBUG_LOGGING=true
 
 
18
  - ANONYMOUS_MODE=true
19
  - TOOL_SUPPORT=true
20
  - SCAN_LIMIT=200000
main.py CHANGED
@@ -1,25 +1,40 @@
1
  #!/usr/bin/env python
2
  # -*- coding: utf-8 -*-
3
 
4
- """
5
- Main application entry point
6
- """
7
-
8
- from fastapi import FastAPI, Request, Response
9
  from fastapi.middleware.cors import CORSMiddleware
10
 
11
  from app.core.config import settings
12
  from app.core import openai
13
  from app.utils.reload_config import RELOAD_CONFIG
 
 
14
 
15
  from granian import Granian
16
 
17
- # Create FastAPI app
18
- app = FastAPI(
19
- title="OpenAI Compatible API Server",
20
- description="An OpenAI-compatible API server for Z.AI chat service",
21
- version="1.0.0",
22
- )
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
23
 
24
  # Add CORS middleware
25
  app.add_middleware(
@@ -52,7 +67,7 @@ def run_server():
52
  interface="asgi",
53
  address="0.0.0.0",
54
  port=settings.LISTEN_PORT,
55
- reload=False, # 生产环境请关闭热重载
56
  **RELOAD_CONFIG,
57
  ).serve()
58
 
 
1
  #!/usr/bin/env python
2
  # -*- coding: utf-8 -*-
3
 
4
+ from contextlib import asynccontextmanager
5
+ from fastapi import FastAPI, Response
 
 
 
6
  from fastapi.middleware.cors import CORSMiddleware
7
 
8
  from app.core.config import settings
9
  from app.core import openai
10
  from app.utils.reload_config import RELOAD_CONFIG
11
+ from app.utils.logger import setup_logger
12
+ from app.utils.token_pool import initialize_token_pool
13
 
14
  from granian import Granian
15
 
16
+
17
+ # Setup logger
18
+ logger = setup_logger(log_dir="logs", debug_mode=settings.DEBUG_LOGGING)
19
+
20
+
21
+ @asynccontextmanager
22
+ async def lifespan(app: FastAPI):
23
+ token_list = settings.auth_token_list
24
+ if token_list:
25
+ token_pool = initialize_token_pool(
26
+ tokens=token_list,
27
+ failure_threshold=settings.TOKEN_FAILURE_THRESHOLD,
28
+ recovery_timeout=settings.TOKEN_RECOVERY_TIMEOUT
29
+ )
30
+
31
+ yield
32
+
33
+ logger.info("🔄 应用正在关闭...")
34
+
35
+
36
+ # Create FastAPI app with lifespan
37
+ app = FastAPI(lifespan=lifespan)
38
 
39
  # Add CORS middleware
40
  app.add_middleware(
 
67
  interface="asgi",
68
  address="0.0.0.0",
69
  port=settings.LISTEN_PORT,
70
+ reload=False, # 生产环境请关闭热重载
71
  **RELOAD_CONFIG,
72
  ).serve()
73
 
pyproject.toml CHANGED
@@ -32,6 +32,8 @@ dependencies = [
32
  "pydantic-core==2.33.2",
33
  "typing-inspection==0.4.1",
34
  "fake-useragent==2.2.0",
 
 
35
  ]
36
 
37
  [project.scripts]
 
32
  "pydantic-core==2.33.2",
33
  "typing-inspection==0.4.1",
34
  "fake-useragent==2.2.0",
35
+ "loguru==0.7.3",
36
+ "httpx==0.27.0"
37
  ]
38
 
39
  [project.scripts]
requirements.txt CHANGED
@@ -1,8 +1,10 @@
1
- fastapi==0.104.1
2
  granian[reload]==2.5.2
3
  requests==2.32.5
 
4
  pydantic==2.11.7
5
  pydantic-settings==2.10.1
6
  pydantic-core==2.33.2
7
  typing-inspection==0.4.1
8
- fake-useragent==2.2.0
 
 
1
+ fastapi==0.116.1
2
  granian[reload]==2.5.2
3
  requests==2.32.5
4
+ httpx==0.27.0
5
  pydantic==2.11.7
6
  pydantic-settings==2.10.1
7
  pydantic-core==2.33.2
8
  typing-inspection==0.4.1
9
+ fake-useragent==2.2.0
10
+ loguru==0.7.3
tests/test_final_verification.py DELETED
@@ -1,56 +0,0 @@
1
- """验证 tools.py 修复后的功能"""
2
-
3
- import sys
4
- sys.path.append('E:\\GitHub\\z.ai2api_python')
5
-
6
- from app.utils.tools import remove_tool_json_content
7
-
8
- def test_remove_tool_json():
9
- print("=" * 60)
10
- print("验证 tools.py 中的 remove_tool_json_content 函数")
11
- print("=" * 60)
12
-
13
- # 测试案例 1: 纯工具调用 JSON(应该被完全移除)
14
- test1 = '{"tool_calls": [{"id": "call_1", "type": "function"}]}'
15
- result1 = remove_tool_json_content(test1)
16
- print(f"\n测试1 - 纯工具调用:")
17
- print(f"输入: {test1}")
18
- print(f"输出: '{result1}'")
19
- print("[PASS] 通过" if result1 == "" else "[FAIL] 失败")
20
-
21
- # 测试案例 2: 混合内容
22
- test2 = '''这是开始文本
23
- {"tool_calls": [{"id": "call_2", "type": "function"}]}
24
- 这是结束文本'''
25
- result2 = remove_tool_json_content(test2)
26
- print(f"\n测试2 - 混合内容:")
27
- print(f"输入: {repr(test2)}")
28
- print(f"输出: {repr(result2)}")
29
- expected2 = "这是开始文本\n\n这是结束文本"
30
- print("[PASS] 通过" if result2 == expected2 else "[FAIL] 失败")
31
-
32
- # 测试案例 3: 普通 JSON(不应被删除)
33
- test3 = '{"data": {"result": "success"}}'
34
- result3 = remove_tool_json_content(test3)
35
- print(f"\n测试3 - 普通JSON:")
36
- print(f"输入: {test3}")
37
- print(f"输出: '{result3}'")
38
- print("[PASS] 通过" if result3 == test3 else "[FAIL] 失败")
39
-
40
- # 测试案例 4: 代码块中的工具调用
41
- test4 = '''正常文本
42
- ```json
43
- {"tool_calls": [{"id": "call_3"}]}
44
- ```
45
- 保留文本'''
46
- result4 = remove_tool_json_content(test4)
47
- print(f"\n测试4 - 代码块中的工具调用:")
48
- print(f"输入: {repr(test4)}")
49
- print(f"输出: {repr(result4)}")
50
- print("[PASS] 通过" if "保留文本" in result4 and "tool_calls" not in result4 else "[FAIL] 失败")
51
-
52
- if __name__ == "__main__":
53
- test_remove_tool_json()
54
- print("\n" + "=" * 60)
55
- print("所有测试完成!正则表达式问题已成功修复。")
56
- print("=" * 60)
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_function_call.py DELETED
@@ -1,70 +0,0 @@
1
- # -*- coding: utf-8 -*-
2
-
3
- import json
4
- import requests
5
-
6
- # API 配置
7
- API_BASE = "http://localhost:8080"
8
- API_KEY = "sk-your-api-key"
9
-
10
- def test_weather_query():
11
- """测试天气查询"""
12
- print("=" * 50)
13
- print("上海天气查询测试")
14
- print("=" * 50)
15
-
16
- # 工具定义
17
- tool = {
18
- "type": "function",
19
- "function": {
20
- "name": "get_weather",
21
- "description": "查询指定城市的天气信息",
22
- "parameters": {
23
- "type": "object",
24
- "properties": {
25
- "city": {"type": "string", "description": "城市名称"},
26
- "date": {"type": "string", "description": "查询日期(可选)"}
27
- },
28
- "required": ["city"]
29
- }
30
- }
31
- }
32
-
33
- # 发送请求
34
- headers = {
35
- "Content-Type": "application/json",
36
- "Authorization": f"Bearer {API_KEY}"
37
- }
38
-
39
- data = {
40
- "model": "GLM-4.5",
41
- "messages": [
42
- {"role": "user", "content": "查询上海2025年9月3日的天气"}
43
- ],
44
- "tools": [tool]
45
- }
46
-
47
- print("\n发送请求...")
48
- response = requests.post(f"{API_BASE}/v1/chat/completions",
49
- headers=headers,
50
- json=data)
51
-
52
- if response.status_code == 200:
53
- result = response.json()
54
- message = result["choices"][0]["message"]
55
-
56
- print("\n模型响应:")
57
- if message.get("tool_calls"):
58
- print("检测到工具调用:")
59
- for tc in message["tool_calls"]:
60
- print(f" - 工具: {tc['function']['name']}")
61
- print(f" - 参数: {tc['function']['arguments']}")
62
- else:
63
- print("未检测到工具调用")
64
- print(f"内容: {message.get('content', '无内容')[:100]}...")
65
- else:
66
- print(f"请求失败: {response.status_code}")
67
- print(f"错误信息: {response.text}")
68
-
69
- if __name__ == "__main__":
70
- test_weather_query()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_multimodal_quick.py CHANGED
@@ -1,3 +1,6 @@
 
 
 
1
  """
2
  glm-4.5v 多模态功能测试
3
  """
@@ -5,9 +8,7 @@ import requests
5
  import json
6
 
7
  # 创建一个1x1像素的红色图片作为测试
8
- tiny_red_image = (
9
- "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
10
- )
11
 
12
  # API配置
13
  api_url = "http://localhost:8080/v1/chat/completions"
@@ -20,36 +21,25 @@ request_data = {
20
  {
21
  "role": "user",
22
  "content": [ # content必须是数组
23
- {
24
- "type": "text",
25
- "text": "这是什么颜色的图片?"
26
- },
27
- {
28
- "type": "image_url",
29
- "image_url": {
30
- "url": tiny_red_image
31
- }
32
- }
33
- ]
34
  }
35
  ],
36
- "stream": False
37
  }
38
 
39
  print("发送的请求:")
40
  print(json.dumps(request_data, indent=2, ensure_ascii=False))
41
- print("\n" + "="*60)
42
 
43
  # 发送请求
44
- headers = {
45
- "Authorization": f"Bearer {api_key}",
46
- "Content-Type": "application/json"
47
- }
48
 
49
  try:
50
  response = requests.post(api_url, json=request_data, headers=headers)
51
  print(f"响应状态码: {response.status_code}")
52
-
53
  if response.status_code == 200:
54
  result = response.json()
55
  print("\n模型回复:")
@@ -57,6 +47,6 @@ try:
57
  else:
58
  print("\n错误响应:")
59
  print(response.text)
60
-
61
  except Exception as e:
62
- print(f"\n发生错误: {e}")
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
  """
5
  glm-4.5v 多模态功能测试
6
  """
 
8
  import json
9
 
10
  # 创建一个1x1像素的红色图片作为测试
11
+ tiny_red_image = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8z8DwHwAFBQIAX8jx0gAAAABJRU5ErkJggg=="
 
 
12
 
13
  # API配置
14
  api_url = "http://localhost:8080/v1/chat/completions"
 
21
  {
22
  "role": "user",
23
  "content": [ # content必须是数组
24
+ {"type": "text", "text": "这是什么颜色的图片?"},
25
+ {"type": "image_url", "image_url": {"url": tiny_red_image}},
26
+ ],
 
 
 
 
 
 
 
 
27
  }
28
  ],
29
+ "stream": False,
30
  }
31
 
32
  print("发送的请求:")
33
  print(json.dumps(request_data, indent=2, ensure_ascii=False))
34
+ print("\n" + "=" * 60)
35
 
36
  # 发送请求
37
+ headers = {"Authorization": f"Bearer {api_key}", "Content-Type": "application/json"}
 
 
 
38
 
39
  try:
40
  response = requests.post(api_url, json=request_data, headers=headers)
41
  print(f"响应状态码: {response.status_code}")
42
+
43
  if response.status_code == 200:
44
  result = response.json()
45
  print("\n模型回复:")
 
47
  else:
48
  print("\n错误响应:")
49
  print(response.text)
50
+
51
  except Exception as e:
52
+ print(f"\n发生错误: {e}")
tests/test_re.py DELETED
@@ -1,226 +0,0 @@
1
- """测试和修复正则表达式问题"""
2
-
3
- import json
4
- import re
5
-
6
- # 原始的正则表达式(来自 tools.py)
7
- TOOL_CALL_FENCE_PATTERN = re.compile(r"```json\s*(\{.*?\})\s*```", re.DOTALL)
8
- TOOL_CALL_INLINE_PATTERN_OLD = re.compile(r"(\{[^{}]{0,10000}\"tool_calls\".*?\})", re.DOTALL)
9
-
10
- # 改进的正则表达式
11
- # 方案1:更精确的匹配 - 只匹配包含 tool_calls 的完整 JSON 对象
12
- TOOL_CALL_INLINE_PATTERN_NEW = re.compile(
13
- r'\{(?:[^{}]|\{[^{}]*\})*"tool_calls"\s*:\s*\[[^\]]*\](?:[^{}]|\{[^{}]*\})*\}',
14
- re.MULTILINE
15
- )
16
-
17
- def remove_tool_json_content_old(text: str) -> str:
18
- """原始的移除工具JSON内容函数"""
19
-
20
- def remove_tool_call_block(match: re.Match) -> str:
21
- json_content = match.group(1)
22
- try:
23
- parsed_data = json.loads(json_content)
24
- if "tool_calls" in parsed_data:
25
- return ""
26
- except (json.JSONDecodeError, AttributeError):
27
- pass
28
- return match.group(0)
29
-
30
- # Remove fenced tool JSON blocks
31
- cleaned_text = TOOL_CALL_FENCE_PATTERN.sub(remove_tool_call_block, text)
32
- # Remove inline tool JSON
33
- cleaned_text = TOOL_CALL_INLINE_PATTERN_OLD.sub("", cleaned_text)
34
- return cleaned_text.strip()
35
-
36
- def remove_tool_json_content_new(text: str) -> str:
37
- """改进的移除工具JSON内容函数 - 使用基于括号平衡的方法"""
38
-
39
- def remove_tool_call_block(match: re.Match) -> str:
40
- json_content = match.group(1)
41
- try:
42
- parsed_data = json.loads(json_content)
43
- if "tool_calls" in parsed_data:
44
- return ""
45
- except (json.JSONDecodeError, AttributeError):
46
- pass
47
- return match.group(0)
48
-
49
- # Step 1: Remove fenced tool JSON blocks
50
- cleaned_text = TOOL_CALL_FENCE_PATTERN.sub(remove_tool_call_block, text)
51
-
52
- # Step 2: Remove inline tool JSON - 使用更智能的方法
53
- # 查找所有可能的 JSON 对象
54
- result = []
55
- i = 0
56
- while i < len(cleaned_text):
57
- if cleaned_text[i] == '{':
58
- # 尝试找到匹配的右括号
59
- brace_count = 1
60
- j = i + 1
61
- in_string = False
62
- escape_next = False
63
-
64
- while j < len(cleaned_text) and brace_count > 0:
65
- if escape_next:
66
- escape_next = False
67
- elif cleaned_text[j] == '\\':
68
- escape_next = True
69
- elif cleaned_text[j] == '"' and not escape_next:
70
- in_string = not in_string
71
- elif not in_string:
72
- if cleaned_text[j] == '{':
73
- brace_count += 1
74
- elif cleaned_text[j] == '}':
75
- brace_count -= 1
76
- j += 1
77
-
78
- if brace_count == 0:
79
- # 找到了完整的 JSON 对象
80
- json_str = cleaned_text[i:j]
81
- try:
82
- parsed = json.loads(json_str)
83
- if "tool_calls" in parsed:
84
- # 这是一个工具调用,跳过它
85
- i = j
86
- continue
87
- except:
88
- pass
89
-
90
- # 不是工具调用或无法解析,保留这个字符
91
- result.append(cleaned_text[i])
92
- i += 1
93
- else:
94
- result.append(cleaned_text[i])
95
- i += 1
96
-
97
- return ''.join(result).strip()
98
-
99
- # 测试用例
100
- test_cases = [
101
- # 测试案例 1: 只有工具调用JSON,应该被完全删除
102
- {
103
- "name": "纯工具调用JSON",
104
- "input": """{"tool_calls": [{"id": "call_1", "type": "function", "function": {"name": "test", "arguments": "{}"}}]}""",
105
- "expected": ""
106
- },
107
-
108
- # 测试案例 2: 包含工具调用的 JSON 代码块
109
- {
110
- "name": "代码块中的工具调用",
111
- "input": """这是一些正常的文本内容。
112
-
113
- ```json
114
- {
115
- "tool_calls": [
116
- {
117
- "id": "call_123",
118
- "type": "function",
119
- "function": {
120
- "name": "test_function",
121
- "arguments": "{\\"param\\": \\"value\\"}"
122
- }
123
- }
124
- ]
125
- }
126
- ```
127
-
128
- 这部分内容应该被保留。""",
129
- "expected": """这是一些正常的文本内容。
130
-
131
-
132
-
133
- 这部分内容应该被保留。"""
134
- },
135
-
136
- # 测试案例 3: 混合内容
137
- {
138
- "name": "混合内容",
139
- "input": """让我为您执行一个函数调用:
140
-
141
- {"tool_calls": [{"id": "call_789", "type": "function", "function": {"name": "search", "arguments": "{\\"query\\": \\"test\\"}"}}]}
142
-
143
- 函数执行结果如下:
144
- - 找到了相关内容
145
- - 处理完成
146
-
147
- 这里还有其他重要信息需要保留。""",
148
- "expected": """让我为您执行一个函数调用:
149
-
150
-
151
-
152
- 函数执行结果如下:
153
- - 找到了相关内容
154
- - 处理完成
155
-
156
- 这里还有其他重要信息需要保留。"""
157
- },
158
-
159
- # 测试案例 4: 不应该被删除的普通 JSON
160
- {
161
- "name": "普通JSON(应保留)",
162
- "input": """这是一个普通的 JSON 示例:
163
- {"data": {"result": "success"}}
164
-
165
- 这不是工具调用,应该保留。""",
166
- "expected": """这是一个普通的 JSON 示例:
167
- {"data": {"result": "success"}}
168
-
169
- 这不是工具调用,应该保留。"""
170
- },
171
-
172
- # 测试案例 5: 嵌套的复杂JSON
173
- {
174
- "name": "嵌套复杂JSON",
175
- "input": """开始文本
176
- {"tool_calls": [{"id": "call_1", "function": {"name": "test", "arguments": "{\\"nested\\": {\\"deep\\": \\"value\\"}}"}}]}
177
- 中间文本
178
- {"normal": {"data": "keep this"}}
179
- 结束文本""",
180
- "expected": """开始文本
181
-
182
- 中间文本
183
- {"normal": {"data": "keep this"}}
184
- 结束文本"""
185
- }
186
- ]
187
-
188
- def run_tests():
189
- print("=" * 80)
190
- print("测试正则表达式处理")
191
- print("=" * 80)
192
-
193
- passed = 0
194
- failed = 0
195
-
196
- for test_case in test_cases:
197
- print(f"\n测试案例: {test_case['name']}")
198
- print("-" * 40)
199
- print("输入文本:")
200
- print(repr(test_case['input']))
201
-
202
- print("\n使用原始函数处理后:")
203
- result_old = remove_tool_json_content_old(test_case['input'])
204
- print(repr(result_old))
205
-
206
- print("\n使用改进函数处理后:")
207
- result_new = remove_tool_json_content_new(test_case['input'])
208
- print(repr(result_new))
209
-
210
- print("\n期望结果:")
211
- print(repr(test_case['expected']))
212
-
213
- # 检查新函数是否正确
214
- if result_new == test_case['expected']:
215
- print("[PASS] 新函数通过测试")
216
- passed += 1
217
- else:
218
- print("[FAIL] 新函数测试失败")
219
- failed += 1
220
-
221
- print("-" * 40)
222
-
223
- print(f"\n\n总结: {passed} 个通过, {failed} 个失败")
224
-
225
- if __name__ == "__main__":
226
- run_tests()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_tool_call.py DELETED
@@ -1,145 +0,0 @@
1
- #!/usr/bin/env python
2
- # -*- coding: utf-8 -*-
3
- """
4
- 测试工具调用功能
5
- """
6
-
7
- import json
8
- import requests
9
-
10
- # 配置
11
- BASE_URL = "http://localhost:8080"
12
- API_KEY = "your-api-key" # 替换为实际的 API key
13
-
14
- def test_tool_call():
15
- """测试工具调用功能"""
16
-
17
- # 定义一个简单的工具
18
- tools = [
19
- {
20
- "type": "function",
21
- "function": {
22
- "name": "get_weather",
23
- "description": "获取指定城市的天气信息",
24
- "parameters": {
25
- "type": "object",
26
- "properties": {
27
- "location": {
28
- "type": "string",
29
- "description": "城市名称,例如:北京、上海"
30
- },
31
- "unit": {
32
- "type": "string",
33
- "description": "温度单位",
34
- "enum": ["celsius", "fahrenheit"]
35
- }
36
- },
37
- "required": ["location"]
38
- }
39
- }
40
- }
41
- ]
42
-
43
- # 构建请求
44
- request_data = {
45
- "model": "GLM-4.5",
46
- "messages": [
47
- {
48
- "role": "user",
49
- "content": "北京的天气怎么样?"
50
- }
51
- ],
52
- "tools": tools,
53
- "tool_choice": "auto",
54
- "stream": False
55
- }
56
-
57
- headers = {
58
- "Content-Type": "application/json",
59
- "Authorization": f"Bearer {API_KEY}"
60
- }
61
-
62
- print("=" * 60)
63
- print("测试工具调用 (非流式)")
64
- print("=" * 60)
65
-
66
- # 发送请求
67
- response = requests.post(
68
- f"{BASE_URL}/v1/chat/completions",
69
- json=request_data,
70
- headers=headers
71
- )
72
-
73
- print(f"状态码: {response.status_code}")
74
-
75
- if response.status_code == 200:
76
- result = response.json()
77
- print("\n响应内容:")
78
- print(json.dumps(result, ensure_ascii=False, indent=2))
79
-
80
- # 检查是否有工具调用
81
- if result.get("choices"):
82
- choice = result["choices"][0]
83
- if choice.get("message", {}).get("tool_calls"):
84
- print("\n✅ 检测到工具调用!")
85
- for tc in choice["message"]["tool_calls"]:
86
- print(f" - 函数: {tc.get('function', {}).get('name')}")
87
- print(f" 参数: {tc.get('function', {}).get('arguments')}")
88
- else:
89
- print("\n⚠️ 未检测到工具调用")
90
- if choice.get("message", {}).get("content"):
91
- print(f"内容: {choice['message']['content'][:200]}")
92
- else:
93
- print(f"\n错误响应: {response.text}")
94
-
95
- # 测试流式响应
96
- print("\n" + "=" * 60)
97
- print("测试工具调用 (流式)")
98
- print("=" * 60)
99
-
100
- request_data["stream"] = True
101
-
102
- response = requests.post(
103
- f"{BASE_URL}/v1/chat/completions",
104
- json=request_data,
105
- headers=headers,
106
- stream=True
107
- )
108
-
109
- print(f"状态码: {response.status_code}")
110
-
111
- if response.status_code == 200:
112
- print("\n流式响应:")
113
- tool_calls_detected = False
114
-
115
- for line in response.iter_lines():
116
- if line:
117
- line_str = line.decode('utf-8')
118
- if line_str.startswith("data: "):
119
- data = line_str[6:]
120
- if data == "[DONE]":
121
- print("流结束")
122
- break
123
-
124
- try:
125
- chunk = json.loads(data)
126
- if chunk.get("choices"):
127
- delta = chunk["choices"][0].get("delta", {})
128
- if delta.get("tool_calls"):
129
- tool_calls_detected = True
130
- print(f"检测到工具调用: {json.dumps(delta['tool_calls'], ensure_ascii=False)}")
131
- elif delta.get("content"):
132
- print(f"内容: {delta['content']}", end="")
133
- except json.JSONDecodeError:
134
- pass
135
-
136
- if tool_calls_detected:
137
- print("\n\n✅ 流式响应中检测到工具调用!")
138
- else:
139
- print("\n\n⚠️ 流式响应中未检测到工具调用")
140
- else:
141
- print(f"\n错误响应: {response.text}")
142
-
143
-
144
- if __name__ == "__main__":
145
- test_tool_call()
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
tests/test_tool_call_fix.py ADDED
@@ -0,0 +1,133 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env python
2
+ # -*- coding: utf-8 -*-
3
+
4
+ """
5
+ 测试工具调用
6
+ """
7
+
8
+ import json
9
+ import urllib.request
10
+ import urllib.parse
11
+ from typing import Dict, Any
12
+
13
+ def test_tool_call():
14
+ """测试工具调用功能"""
15
+
16
+ # 测试请求
17
+ test_request = {
18
+ "model": "glm-4.5",
19
+ "messages": [
20
+ {
21
+ "role": "user",
22
+ "content": "请打开Google网站"
23
+ }
24
+ ],
25
+ "tools": [
26
+ {
27
+ "type": "function",
28
+ "function": {
29
+ "name": "playwri-browser_navigate",
30
+ "description": "Navigate to a URL in the browser",
31
+ "parameters": {
32
+ "type": "object",
33
+ "properties": {
34
+ "url": {
35
+ "type": "string",
36
+ "description": "The URL to navigate to"
37
+ }
38
+ },
39
+ "required": ["url"]
40
+ }
41
+ }
42
+ }
43
+ ],
44
+ "stream": True
45
+ }
46
+
47
+ print("🚀 发送工具调用测试请求...")
48
+ print(f"📦 请求内容: {json.dumps(test_request, ensure_ascii=False, indent=2)}")
49
+
50
+ # 准备HTTP请求
51
+ url = "http://localhost:8080/v1/chat/completions"
52
+ data = json.dumps(test_request).encode('utf-8')
53
+
54
+ req = urllib.request.Request(url, data=data)
55
+ req.add_header('Content-Type', 'application/json')
56
+ req.add_header('Authorization', 'Bearer sk-test-key')
57
+
58
+ try:
59
+ with urllib.request.urlopen(req) as response:
60
+ print(f"📈 响应状态: {response.status}")
61
+
62
+ if response.status == 200:
63
+ print("✅ 开始接收流式响应...")
64
+
65
+ tool_calls_found = []
66
+ chunk_count = 0
67
+
68
+ for line in response:
69
+ line = line.decode('utf-8').strip()
70
+ if line.startswith('data: '):
71
+ chunk_count += 1
72
+ data_str = line[6:] # 去掉 'data: ' 前缀
73
+
74
+ if data_str == '[DONE]':
75
+ print("🏁 接收到结束信号")
76
+ break
77
+
78
+ try:
79
+ chunk = json.loads(data_str)
80
+
81
+ # 检查是否包含工具调用
82
+ if 'choices' in chunk and chunk['choices']:
83
+ choice = chunk['choices'][0]
84
+ if 'delta' in choice and 'tool_calls' in choice['delta']:
85
+ tool_calls = choice['delta']['tool_calls']
86
+ if tool_calls:
87
+ for tool_call in tool_calls:
88
+ print(f"🔧 发现工具调用: {json.dumps(tool_call, ensure_ascii=False, indent=2)}")
89
+ tool_calls_found.append(tool_call)
90
+
91
+ # 检查完成原因
92
+ if choice.get('finish_reason') == 'tool_calls':
93
+ print("✅ 工具调用完成")
94
+
95
+ except json.JSONDecodeError as e:
96
+ print(f"❌ JSON解析错误: {e}, 数据: {data_str[:200]}")
97
+
98
+ print(f"📊 总共接收到 {chunk_count} 个数据块")
99
+ print(f"🔧 发现 {len(tool_calls_found)} 个工具调用")
100
+
101
+ # 分析工具调用格式
102
+ for i, tool_call in enumerate(tool_calls_found):
103
+ print(f"\n🔍 工具调用 {i+1} 分析:")
104
+ print(f" ID: {tool_call.get('id', 'N/A')}")
105
+ print(f" 类型: {tool_call.get('type', 'N/A')}")
106
+
107
+ if 'function' in tool_call:
108
+ func = tool_call['function']
109
+ print(f" 函数名: {func.get('name', 'N/A')}")
110
+
111
+ arguments = func.get('arguments', '')
112
+ print(f" 参数类型: {type(arguments)}")
113
+ print(f" 参数内容: {arguments}")
114
+
115
+ # 尝试解析参数
116
+ if isinstance(arguments, str) and arguments:
117
+ try:
118
+ parsed_args = json.loads(arguments)
119
+ print(f" ✅ 参数解析成功: {parsed_args}")
120
+ except json.JSONDecodeError as e:
121
+ print(f" ❌ 参数解析失败: {e}")
122
+ elif isinstance(arguments, dict):
123
+ print(f" ⚠️ 参数是对象格式(应该是字符串): {arguments}")
124
+
125
+ else:
126
+ error_text = response.read().decode('utf-8')
127
+ print(f"❌ 请求失败: {error_text}")
128
+
129
+ except Exception as e:
130
+ print(f"❌ 请求异常: {e}")
131
+
132
+ if __name__ == "__main__":
133
+ test_tool_call()
tokens.txt.example ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # 认证Token配置文件
2
+ #
3
+ # 说明:
4
+ # 1. 支持两种格式:每行一个token 或 逗号分隔的token
5
+ # 2. 只包含认证用户token (role: "user"),不要添加匿名用户token (role: "guest")
6
+ # 3. 系统会自动去重和验证token有效性
7
+ # 4. 修改此文件后无需重启服务,系统会自动重新加载
8
+ # 5. 自动跳过空格、换行符和空token
9
+ #
10
+ # 格式1:纯换行分隔
11
+ # token1
12
+ # token2
13
+ # token3
14
+
15
+ # 格式2:纯逗号分隔
16
+ # token1,token2,token3
17
+
18
+ # 格式3:混合格式
19
+ # token1,token2
20
+ # token3
21
+ # token4,token5,token6
22
+ # token7
23
+
24
+ # 请在下方添加您的认证用户token(使用任一格式):
25
+