ZyphrZero
commited on
Commit
·
e5845a1
1
Parent(s):
901d05b
♻️ refactor(zai_transformer): 重构工具调用处理逻辑
Browse files- 添加新的工具调用状态管理机制
- 实现工具调用参数解析和错误处理
- 添加工具调用开始、参数和完成的chunk创建方法
- 优化other阶段处理,特别是工具调用结束标记的检测
- 添加详细的日志记录以便调试工具调用过程
- app/__init__.py +2 -3
- app/core/__init__.py +4 -5
- app/core/config.py +16 -12
- app/core/openai.py +311 -136
- app/core/response_handlers.py +0 -333
- app/core/zai_transformer.py +648 -0
- app/models/__init__.py +3 -4
- app/models/schemas.py +4 -4
- app/utils/__init__.py +4 -5
- app/utils/helpers.py +0 -211
- app/utils/logger.py +103 -0
- app/utils/reload_config.py +3 -0
- app/utils/sse_parser.py +0 -127
- app/utils/sse_tool_handler.py +284 -0
- app/utils/tools.py +0 -325
- main.py +6 -5
- pyproject.toml +1 -0
- requirements.txt +2 -1
- tests/test_final_verification.py +0 -56
- tests/test_function_call.py +0 -70
- tests/test_multimodal_quick.py +13 -23
- tests/test_re.py +0 -226
- tests/test_tool_call.py +0 -145
app/__init__.py
CHANGED
|
@@ -1,6 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 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 |
-
|
| 3 |
-
"""
|
| 4 |
|
| 5 |
-
from app.core import config,
|
| 6 |
|
| 7 |
-
__all__ = ["config", "
|
|
|
|
| 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,6 +1,5 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
"""
|
| 4 |
|
| 5 |
import os
|
| 6 |
from typing import Dict, Optional
|
|
@@ -9,29 +8,34 @@ from pydantic_settings import BaseSettings
|
|
| 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(
|
| 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(
|
|
|
|
|
|
|
| 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 +48,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, Optional
|
|
|
|
| 8 |
|
| 9 |
class Settings(BaseSettings):
|
| 10 |
"""Application settings"""
|
| 11 |
+
|
| 12 |
# API Configuration
|
| 13 |
API_ENDPOINT: str = os.getenv("API_ENDPOINT", "https://chat.z.ai/api/chat/completions")
|
| 14 |
AUTH_TOKEN: str = os.getenv("AUTH_TOKEN", "sk-your-api-key")
|
| 15 |
+
BACKUP_TOKEN: str = os.getenv(
|
| 16 |
+
"BACKUP_TOKEN",
|
| 17 |
+
"eyJhbGciOiJFUzI1NiIsInR5cCI6IkpXVCJ9.eyJpZCI6IjMxNmJjYjQ4LWZmMmYtNGExNS04NTNkLWYyYTI5YjY3ZmYwZiIsImVtYWlsIjoiR3Vlc3QtMTc1NTg0ODU4ODc4OEBndWVzdC5jb20ifQ.PktllDySS3trlyuFpTeIZf-7hl8Qu1qYF3BxjgIul0BrNux2nX9hVzIjthLXKMWAf9V0qM8Vm_iyDqkjPGsaiQ",
|
| 18 |
+
)
|
| 19 |
+
|
| 20 |
# Model Configuration
|
| 21 |
PRIMARY_MODEL: str = os.getenv("PRIMARY_MODEL", "GLM-4.5")
|
| 22 |
THINKING_MODEL: str = os.getenv("THINKING_MODEL", "GLM-4.5-Thinking")
|
| 23 |
SEARCH_MODEL: str = os.getenv("SEARCH_MODEL", "GLM-4.5-Search")
|
| 24 |
AIR_MODEL: str = os.getenv("AIR_MODEL", "GLM-4.5-Air")
|
| 25 |
+
|
| 26 |
# Server Configuration
|
| 27 |
LISTEN_PORT: int = int(os.getenv("LISTEN_PORT", "8080"))
|
| 28 |
DEBUG_LOGGING: bool = os.getenv("DEBUG_LOGGING", "true").lower() == "true"
|
| 29 |
+
|
| 30 |
# Feature Configuration
|
| 31 |
+
THINKING_PROCESSING: str = os.getenv(
|
| 32 |
+
"THINKING_PROCESSING", "think"
|
| 33 |
+
) # strip: 去除<details>标签;think: 转为<span>标签;raw: 保留原样
|
| 34 |
ANONYMOUS_MODE: bool = os.getenv("ANONYMOUS_MODE", "true").lower() == "true"
|
| 35 |
TOOL_SUPPORT: bool = os.getenv("TOOL_SUPPORT", "true").lower() == "true"
|
| 36 |
SCAN_LIMIT: int = int(os.getenv("SCAN_LIMIT", "200000"))
|
| 37 |
SKIP_AUTH_TOKEN: bool = os.getenv("SKIP_AUTH_TOKEN", "false").lower() == "true"
|
| 38 |
+
|
| 39 |
# Browser Headers
|
| 40 |
CLIENT_HEADERS: Dict[str, str] = {
|
| 41 |
"Content-Type": "application/json",
|
|
|
|
| 48 |
"X-FE-Version": "prod-fe-1.0.70",
|
| 49 |
"Origin": "https://chat.z.ai",
|
| 50 |
}
|
| 51 |
+
|
| 52 |
class Config:
|
| 53 |
env_file = ".env"
|
| 54 |
|
| 55 |
|
| 56 |
+
settings = Settings()
|
app/core/openai.py
CHANGED
|
@@ -1,24 +1,27 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 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 |
-
|
| 14 |
-
|
| 15 |
-
|
| 16 |
-
|
| 17 |
-
|
| 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 +29,322 @@ async def list_models():
|
|
| 26 |
current_time = int(time.time())
|
| 27 |
response = ModelsResponse(
|
| 28 |
data=[
|
| 29 |
-
Model(
|
| 30 |
-
|
| 31 |
-
|
| 32 |
-
|
| 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 |
-
|
| 57 |
-
|
| 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 |
-
|
| 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 |
-
|
| 72 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 73 |
-
|
| 74 |
-
|
| 75 |
else:
|
| 76 |
-
|
| 77 |
-
|
| 78 |
-
|
| 79 |
-
|
| 80 |
-
|
| 81 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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
-
|
| 173 |
import traceback
|
| 174 |
-
|
| 175 |
-
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
|
|
|
| 3 |
|
| 4 |
import time
|
| 5 |
+
import json
|
| 6 |
from datetime import datetime
|
| 7 |
+
from typing import List, Dict, Any
|
| 8 |
from fastapi import APIRouter, Header, HTTPException
|
| 9 |
from fastapi.responses import StreamingResponse
|
| 10 |
+
import httpx
|
| 11 |
|
| 12 |
from app.core.config import settings
|
| 13 |
+
from app.models.schemas import OpenAIRequest, Message, ModelsResponse, Model
|
| 14 |
+
from app.utils.logger import get_logger
|
| 15 |
+
from app.core.zai_transformer import ZAITransformer, generate_uuid
|
| 16 |
+
from app.utils.sse_tool_handler import SSEToolHandler
|
| 17 |
+
|
| 18 |
+
logger = get_logger()
|
|
|
|
| 19 |
|
| 20 |
router = APIRouter()
|
| 21 |
|
| 22 |
+
# 全局转换器实例
|
| 23 |
+
transformer = ZAITransformer()
|
| 24 |
+
|
| 25 |
|
| 26 |
@router.get("/v1/models")
|
| 27 |
async def list_models():
|
|
|
|
| 29 |
current_time = int(time.time())
|
| 30 |
response = ModelsResponse(
|
| 31 |
data=[
|
| 32 |
+
Model(id=settings.PRIMARY_MODEL, created=current_time, owned_by="z.ai"),
|
| 33 |
+
Model(id=settings.THINKING_MODEL, created=current_time, owned_by="z.ai"),
|
| 34 |
+
Model(id=settings.SEARCH_MODEL, created=current_time, owned_by="z.ai"),
|
| 35 |
+
Model(id=settings.AIR_MODEL, created=current_time, owned_by="z.ai"),
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 36 |
]
|
| 37 |
)
|
| 38 |
return response
|
| 39 |
|
| 40 |
|
| 41 |
@router.post("/v1/chat/completions")
|
| 42 |
+
async def chat_completions(request: OpenAIRequest, authorization: str = Header(...)):
|
| 43 |
+
"""Handle chat completion requests with ZAI transformer"""
|
| 44 |
+
logger.debug("收到chat completions请求")
|
| 45 |
+
|
|
|
|
|
|
|
|
|
|
| 46 |
try:
|
| 47 |
# Validate API key (skip if SKIP_AUTH_TOKEN is enabled)
|
| 48 |
if not settings.SKIP_AUTH_TOKEN:
|
| 49 |
if not authorization.startswith("Bearer "):
|
| 50 |
+
logger.debug("缺少或无效的Authorization头")
|
| 51 |
raise HTTPException(status_code=401, detail="Missing or invalid Authorization header")
|
| 52 |
+
|
| 53 |
api_key = authorization[7:]
|
| 54 |
if api_key != settings.AUTH_TOKEN:
|
| 55 |
+
logger.debug(f"无效的API key: {api_key}")
|
| 56 |
raise HTTPException(status_code=401, detail="Invalid API key")
|
| 57 |
+
|
| 58 |
+
logger.debug(f"API key验证通过")
|
| 59 |
else:
|
| 60 |
+
logger.debug("SKIP_AUTH_TOKEN已启用,跳过API key验证")
|
| 61 |
+
|
| 62 |
+
logger.debug(f"请求解析成功 - 模型: {request.model}, 流式: {request.stream}, 消息数: {len(request.messages)}")
|
| 63 |
+
|
| 64 |
+
# 使用新的转换器转换请求
|
| 65 |
+
request_dict = request.model_dump()
|
| 66 |
+
transformed = await transformer.transform_request_in(request_dict)
|
| 67 |
+
|
| 68 |
+
logger.debug(
|
| 69 |
+
f"请求转换完成 - 上游模型: {transformed['body']['model']}, "
|
| 70 |
+
f"enable_thinking: {transformed['body']['features']['enable_thinking']}, "
|
| 71 |
+
f"mcp_servers: {transformed['body'].get('mcp_servers', [])}"
|
| 72 |
)
|
| 73 |
+
|
| 74 |
+
# 调用上游API
|
| 75 |
+
async def stream_response():
|
| 76 |
+
"""流式响应生成器"""
|
| 77 |
+
try:
|
| 78 |
+
async with httpx.AsyncClient(timeout=60.0) as client:
|
| 79 |
+
# 发送请求到上游
|
| 80 |
+
async with client.stream(
|
| 81 |
+
"POST",
|
| 82 |
+
transformed["config"]["url"],
|
| 83 |
+
json=transformed["body"],
|
| 84 |
+
headers=transformed["config"]["headers"],
|
| 85 |
+
) as response:
|
| 86 |
+
if response.status_code != 200:
|
| 87 |
+
logger.error(f"上游返回错误: {response.status_code}")
|
| 88 |
+
error_text = await response.aread()
|
| 89 |
+
logger.error(f"错误详情: {error_text.decode('utf-8', errors='ignore')}")
|
| 90 |
+
yield f"data: {json.dumps({'error': 'Upstream error'})}\n\n"
|
| 91 |
+
return
|
| 92 |
+
|
| 93 |
+
# 初始化工具处理器(如果需要)
|
| 94 |
+
has_tools = transformed["body"].get("tools") is not None
|
| 95 |
+
tool_handler = None
|
| 96 |
+
if has_tools:
|
| 97 |
+
chat_id = transformed["body"]["chat_id"]
|
| 98 |
+
model = request.model
|
| 99 |
+
tool_handler = SSEToolHandler(chat_id, model)
|
| 100 |
+
logger.debug(f"初始化工具处理器 - chat_id: {chat_id}")
|
| 101 |
+
|
| 102 |
+
# 处理状态
|
| 103 |
+
has_thinking = False
|
| 104 |
+
thinking_signature = None
|
| 105 |
+
|
| 106 |
+
# 处理SSE流
|
| 107 |
+
buffer = ""
|
| 108 |
+
async for line in response.aiter_lines():
|
| 109 |
+
if not line:
|
| 110 |
+
continue
|
| 111 |
+
|
| 112 |
+
# 累积到buffer处理完整的数据行
|
| 113 |
+
buffer += line + "\n"
|
| 114 |
+
|
| 115 |
+
# 检查是否有完整的data行
|
| 116 |
+
while "\n" in buffer:
|
| 117 |
+
current_line, buffer = buffer.split("\n", 1)
|
| 118 |
+
if not current_line.strip():
|
| 119 |
+
continue
|
| 120 |
+
|
| 121 |
+
if current_line.startswith("data:"):
|
| 122 |
+
chunk_str = current_line[5:].strip()
|
| 123 |
+
if not chunk_str or chunk_str == "[DONE]":
|
| 124 |
+
if chunk_str == "[DONE]":
|
| 125 |
+
yield "data: [DONE]\n\n"
|
| 126 |
+
continue
|
| 127 |
+
|
| 128 |
+
try:
|
| 129 |
+
chunk = json.loads(chunk_str)
|
| 130 |
+
|
| 131 |
+
if chunk.get("type") == "chat:completion":
|
| 132 |
+
data = chunk.get("data", {})
|
| 133 |
+
phase = data.get("phase")
|
| 134 |
+
|
| 135 |
+
# 处理工具调用
|
| 136 |
+
if phase == "tool_call" and tool_handler:
|
| 137 |
+
for output in tool_handler.process_tool_call_phase(data, True):
|
| 138 |
+
yield output
|
| 139 |
+
|
| 140 |
+
# 处理其他阶段(工具结束)
|
| 141 |
+
elif phase == "other" and tool_handler:
|
| 142 |
+
for output in tool_handler.process_other_phase(data, True):
|
| 143 |
+
yield output
|
| 144 |
+
|
| 145 |
+
# 处理思考内容
|
| 146 |
+
elif phase == "thinking":
|
| 147 |
+
if not has_thinking:
|
| 148 |
+
has_thinking = True
|
| 149 |
+
# 发送初始角色
|
| 150 |
+
role_chunk = {
|
| 151 |
+
"choices": [
|
| 152 |
+
{
|
| 153 |
+
"delta": {"role": "assistant"},
|
| 154 |
+
"finish_reason": None,
|
| 155 |
+
"index": 0,
|
| 156 |
+
"logprobs": None,
|
| 157 |
+
}
|
| 158 |
+
],
|
| 159 |
+
"created": int(time.time()),
|
| 160 |
+
"id": transformed["body"]["chat_id"],
|
| 161 |
+
"model": request.model,
|
| 162 |
+
"object": "chat.completion.chunk",
|
| 163 |
+
"system_fingerprint": "fp_zai_001",
|
| 164 |
+
}
|
| 165 |
+
yield f"data: {json.dumps(role_chunk)}\n\n"
|
| 166 |
+
|
| 167 |
+
delta_content = data.get("delta_content", "")
|
| 168 |
+
if delta_content:
|
| 169 |
+
# 处理思考内容格式
|
| 170 |
+
if delta_content.startswith("<details"):
|
| 171 |
+
content = (
|
| 172 |
+
delta_content.split("</summary>\n>")[-1].strip()
|
| 173 |
+
if "</summary>\n>" in delta_content
|
| 174 |
+
else delta_content
|
| 175 |
+
)
|
| 176 |
+
else:
|
| 177 |
+
content = delta_content
|
| 178 |
+
|
| 179 |
+
thinking_chunk = {
|
| 180 |
+
"choices": [
|
| 181 |
+
{
|
| 182 |
+
"delta": {
|
| 183 |
+
"role": "assistant",
|
| 184 |
+
"thinking": {"content": content},
|
| 185 |
+
},
|
| 186 |
+
"finish_reason": None,
|
| 187 |
+
"index": 0,
|
| 188 |
+
"logprobs": None,
|
| 189 |
+
}
|
| 190 |
+
],
|
| 191 |
+
"created": int(time.time()),
|
| 192 |
+
"id": transformed["body"]["chat_id"],
|
| 193 |
+
"model": request.model,
|
| 194 |
+
"object": "chat.completion.chunk",
|
| 195 |
+
"system_fingerprint": "fp_zai_001",
|
| 196 |
+
}
|
| 197 |
+
yield f"data: {json.dumps(thinking_chunk)}\n\n"
|
| 198 |
+
|
| 199 |
+
# 处理答案内容
|
| 200 |
+
elif phase == "answer":
|
| 201 |
+
edit_content = data.get("edit_content", "")
|
| 202 |
+
delta_content = data.get("delta_content", "")
|
| 203 |
+
|
| 204 |
+
# 处理思考结束和答案开始
|
| 205 |
+
if edit_content and "</details>\n" in edit_content:
|
| 206 |
+
if has_thinking:
|
| 207 |
+
# 发送思考签名
|
| 208 |
+
thinking_signature = str(int(time.time() * 1000))
|
| 209 |
+
sig_chunk = {
|
| 210 |
+
"choices": [
|
| 211 |
+
{
|
| 212 |
+
"delta": {
|
| 213 |
+
"role": "assistant",
|
| 214 |
+
"thinking": {
|
| 215 |
+
"content": "",
|
| 216 |
+
"signature": thinking_signature,
|
| 217 |
+
},
|
| 218 |
+
},
|
| 219 |
+
"finish_reason": None,
|
| 220 |
+
"index": 0,
|
| 221 |
+
"logprobs": None,
|
| 222 |
+
}
|
| 223 |
+
],
|
| 224 |
+
"created": int(time.time()),
|
| 225 |
+
"id": transformed["body"]["chat_id"],
|
| 226 |
+
"model": request.model,
|
| 227 |
+
"object": "chat.completion.chunk",
|
| 228 |
+
"system_fingerprint": "fp_zai_001",
|
| 229 |
+
}
|
| 230 |
+
yield f"data: {json.dumps(sig_chunk)}\n\n"
|
| 231 |
+
|
| 232 |
+
# 提取答案内容
|
| 233 |
+
content_after = edit_content.split("</details>\n")[-1]
|
| 234 |
+
if content_after:
|
| 235 |
+
content_chunk = {
|
| 236 |
+
"choices": [
|
| 237 |
+
{
|
| 238 |
+
"delta": {
|
| 239 |
+
"role": "assistant",
|
| 240 |
+
"content": content_after,
|
| 241 |
+
},
|
| 242 |
+
"finish_reason": None,
|
| 243 |
+
"index": 0,
|
| 244 |
+
"logprobs": None,
|
| 245 |
+
}
|
| 246 |
+
],
|
| 247 |
+
"created": int(time.time()),
|
| 248 |
+
"id": transformed["body"]["chat_id"],
|
| 249 |
+
"model": request.model,
|
| 250 |
+
"object": "chat.completion.chunk",
|
| 251 |
+
"system_fingerprint": "fp_zai_001",
|
| 252 |
+
}
|
| 253 |
+
yield f"data: {json.dumps(content_chunk)}\n\n"
|
| 254 |
+
|
| 255 |
+
# 处理增量内容
|
| 256 |
+
elif delta_content:
|
| 257 |
+
# 如果还没有发送角色
|
| 258 |
+
if not has_thinking:
|
| 259 |
+
role_chunk = {
|
| 260 |
+
"choices": [
|
| 261 |
+
{
|
| 262 |
+
"delta": {"role": "assistant"},
|
| 263 |
+
"finish_reason": None,
|
| 264 |
+
"index": 0,
|
| 265 |
+
"logprobs": None,
|
| 266 |
+
}
|
| 267 |
+
],
|
| 268 |
+
"created": int(time.time()),
|
| 269 |
+
"id": transformed["body"]["chat_id"],
|
| 270 |
+
"model": request.model,
|
| 271 |
+
"object": "chat.completion.chunk",
|
| 272 |
+
"system_fingerprint": "fp_zai_001",
|
| 273 |
+
}
|
| 274 |
+
yield f"data: {json.dumps(role_chunk)}\n\n"
|
| 275 |
+
|
| 276 |
+
content_chunk = {
|
| 277 |
+
"choices": [
|
| 278 |
+
{
|
| 279 |
+
"delta": {
|
| 280 |
+
"role": "assistant",
|
| 281 |
+
"content": delta_content,
|
| 282 |
+
},
|
| 283 |
+
"finish_reason": None,
|
| 284 |
+
"index": 0,
|
| 285 |
+
"logprobs": None,
|
| 286 |
+
}
|
| 287 |
+
],
|
| 288 |
+
"created": int(time.time()),
|
| 289 |
+
"id": transformed["body"]["chat_id"],
|
| 290 |
+
"model": request.model,
|
| 291 |
+
"object": "chat.completion.chunk",
|
| 292 |
+
"system_fingerprint": "fp_zai_001",
|
| 293 |
+
}
|
| 294 |
+
yield f"data: {json.dumps(content_chunk)}\n\n"
|
| 295 |
+
|
| 296 |
+
# 处理完成
|
| 297 |
+
if data.get("usage"):
|
| 298 |
+
finish_chunk = {
|
| 299 |
+
"choices": [
|
| 300 |
+
{
|
| 301 |
+
"delta": {"role": "assistant", "content": ""},
|
| 302 |
+
"finish_reason": "stop",
|
| 303 |
+
"index": 0,
|
| 304 |
+
"logprobs": None,
|
| 305 |
+
}
|
| 306 |
+
],
|
| 307 |
+
"usage": data["usage"],
|
| 308 |
+
"created": int(time.time()),
|
| 309 |
+
"id": transformed["body"]["chat_id"],
|
| 310 |
+
"model": request.model,
|
| 311 |
+
"object": "chat.completion.chunk",
|
| 312 |
+
"system_fingerprint": "fp_zai_001",
|
| 313 |
+
}
|
| 314 |
+
yield f"data: {json.dumps(finish_chunk)}\n\n"
|
| 315 |
+
yield "data: [DONE]\n\n"
|
| 316 |
+
|
| 317 |
+
except json.JSONDecodeError as e:
|
| 318 |
+
logger.debug(f"JSON解析错误: {e}, 内容: {chunk_str[:100]}")
|
| 319 |
+
except Exception as e:
|
| 320 |
+
logger.error(f"处理chunk错误: {e}")
|
| 321 |
+
|
| 322 |
+
# 确保发送结束信号
|
| 323 |
+
if not tool_handler or not tool_handler.state.has_tool_call:
|
| 324 |
+
yield "data: [DONE]\n\n"
|
| 325 |
+
|
| 326 |
+
except Exception as e:
|
| 327 |
+
logger.error(f"流处理错误: {e}")
|
| 328 |
+
import traceback
|
| 329 |
+
|
| 330 |
+
logger.error(traceback.format_exc())
|
| 331 |
+
yield f"data: {json.dumps({'error': str(e)})}\n\n"
|
| 332 |
+
|
| 333 |
+
# 返回流式响应
|
| 334 |
+
return StreamingResponse(
|
| 335 |
+
stream_response(),
|
| 336 |
+
media_type="text/event-stream",
|
| 337 |
+
headers={
|
| 338 |
+
"Cache-Control": "no-cache",
|
| 339 |
+
"Connection": "keep-alive",
|
| 340 |
},
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 341 |
)
|
| 342 |
+
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 343 |
except HTTPException:
|
| 344 |
raise
|
| 345 |
except Exception as e:
|
| 346 |
+
logger.error(f"处理请求时发生错误: {str(e)}")
|
| 347 |
import traceback
|
| 348 |
+
|
| 349 |
+
logger.error(f"错误堆栈: {traceback.format_exc()}")
|
| 350 |
+
raise HTTPException(status_code=500, detail=f"Internal server error: {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))
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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|
|
|
|
|
|
|
|
|
| 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 |
+
|
| 18 |
+
logger = get_logger()
|
| 19 |
+
|
| 20 |
+
# 全局 UserAgent 实例(单例模式)
|
| 21 |
+
_user_agent_instance = None
|
| 22 |
+
|
| 23 |
+
|
| 24 |
+
def get_user_agent_instance() -> UserAgent:
|
| 25 |
+
"""获取或创建 UserAgent 实例(单例模式)"""
|
| 26 |
+
global _user_agent_instance
|
| 27 |
+
if _user_agent_instance is None:
|
| 28 |
+
_user_agent_instance = UserAgent()
|
| 29 |
+
return _user_agent_instance
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
def get_dynamic_headers(chat_id: str = "") -> Dict[str, str]:
|
| 33 |
+
"""生成动态浏览器headers,包含随机User-Agent"""
|
| 34 |
+
ua = get_user_agent_instance()
|
| 35 |
+
|
| 36 |
+
# 随机选择浏览器类型,偏向Chrome和Edge
|
| 37 |
+
browser_choices = ["chrome", "chrome", "chrome", "edge", "edge", "firefox", "safari"]
|
| 38 |
+
browser_type = random.choice(browser_choices)
|
| 39 |
+
|
| 40 |
+
try:
|
| 41 |
+
if browser_type == "chrome":
|
| 42 |
+
user_agent = ua.chrome
|
| 43 |
+
elif browser_type == "edge":
|
| 44 |
+
user_agent = ua.edge
|
| 45 |
+
elif browser_type == "firefox":
|
| 46 |
+
user_agent = ua.firefox
|
| 47 |
+
elif browser_type == "safari":
|
| 48 |
+
user_agent = ua.safari
|
| 49 |
+
else:
|
| 50 |
+
user_agent = ua.random
|
| 51 |
+
except:
|
| 52 |
+
user_agent = ua.random
|
| 53 |
+
|
| 54 |
+
# 提取版本信息
|
| 55 |
+
chrome_version = "139"
|
| 56 |
+
edge_version = "139"
|
| 57 |
+
|
| 58 |
+
if "Chrome/" in user_agent:
|
| 59 |
+
try:
|
| 60 |
+
chrome_version = user_agent.split("Chrome/")[1].split(".")[0]
|
| 61 |
+
except:
|
| 62 |
+
pass
|
| 63 |
+
|
| 64 |
+
if "Edg/" in user_agent:
|
| 65 |
+
try:
|
| 66 |
+
edge_version = user_agent.split("Edg/")[1].split(".")[0]
|
| 67 |
+
sec_ch_ua = f'"Microsoft Edge";v="{edge_version}", "Chromium";v="{chrome_version}", "Not_A Brand";v="24"'
|
| 68 |
+
except:
|
| 69 |
+
sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
|
| 70 |
+
elif "Firefox/" in user_agent:
|
| 71 |
+
sec_ch_ua = None # Firefox不使用sec-ch-ua
|
| 72 |
+
else:
|
| 73 |
+
sec_ch_ua = f'"Not_A Brand";v="8", "Chromium";v="{chrome_version}", "Google Chrome";v="{chrome_version}"'
|
| 74 |
+
|
| 75 |
+
headers = {
|
| 76 |
+
"Content-Type": "application/json",
|
| 77 |
+
"Accept": "application/json, text/event-stream",
|
| 78 |
+
"User-Agent": user_agent,
|
| 79 |
+
"Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8",
|
| 80 |
+
"X-FE-Version": "prod-fe-1.0.77",
|
| 81 |
+
"Origin": "https://chat.z.ai",
|
| 82 |
+
}
|
| 83 |
+
|
| 84 |
+
if sec_ch_ua:
|
| 85 |
+
headers["sec-ch-ua"] = sec_ch_ua
|
| 86 |
+
headers["sec-ch-ua-mobile"] = "?0"
|
| 87 |
+
headers["sec-ch-ua-platform"] = '"Windows"'
|
| 88 |
+
|
| 89 |
+
if chat_id:
|
| 90 |
+
headers["Referer"] = f"https://chat.z.ai/c/{chat_id}"
|
| 91 |
+
else:
|
| 92 |
+
headers["Referer"] = "https://chat.z.ai/"
|
| 93 |
+
|
| 94 |
+
logger.debug(f"使用动态User-Agent: {user_agent[:80]}...")
|
| 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 |
+
logger.debug("匿名模式:获取新的访客令牌")
|
| 108 |
+
headers = get_dynamic_headers()
|
| 109 |
+
response = requests.get("https://chat.z.ai/api/v1/auths/", headers=headers, timeout=10)
|
| 110 |
+
if response.status_code == 200:
|
| 111 |
+
data = response.json()
|
| 112 |
+
token = data.get("token", "")
|
| 113 |
+
if token:
|
| 114 |
+
logger.debug(f"成功获取访客令牌: {token[:20]}...")
|
| 115 |
+
return token
|
| 116 |
+
except Exception as e:
|
| 117 |
+
logger.warning(f"获取访客令牌失败: {e}")
|
| 118 |
+
|
| 119 |
+
# 使用备份令牌
|
| 120 |
+
logger.debug("使用备份令牌")
|
| 121 |
+
return settings.BACKUP_TOKEN
|
| 122 |
+
|
| 123 |
+
|
| 124 |
+
class ZAITransformer:
|
| 125 |
+
"""ZAI转换器类"""
|
| 126 |
+
|
| 127 |
+
def __init__(self):
|
| 128 |
+
"""初始化转换器"""
|
| 129 |
+
self.name = "zai"
|
| 130 |
+
self.base_url = "https://chat.z.ai"
|
| 131 |
+
self.api_url = settings.API_ENDPOINT
|
| 132 |
+
self.auth_url = f"{self.base_url}/api/v1/auths/"
|
| 133 |
+
|
| 134 |
+
# 模型映射(保留原有逻辑)
|
| 135 |
+
self.model_mapping = {
|
| 136 |
+
settings.PRIMARY_MODEL: "0727-360B-API", # GLM-4.5
|
| 137 |
+
settings.THINKING_MODEL: "0727-360B-API", # GLM-4.5-Thinking
|
| 138 |
+
settings.SEARCH_MODEL: "0727-360B-API", # GLM-4.5-Search
|
| 139 |
+
settings.AIR_MODEL: "0727-106B-API", # GLM-4.5-Air
|
| 140 |
+
}
|
| 141 |
+
|
| 142 |
+
async def get_token(self) -> str:
|
| 143 |
+
"""异步获取认证令牌"""
|
| 144 |
+
if settings.ANONYMOUS_MODE:
|
| 145 |
+
try:
|
| 146 |
+
logger.debug("匿名模式:异步获取新的访客令牌")
|
| 147 |
+
headers = get_dynamic_headers()
|
| 148 |
+
async with httpx.AsyncClient() as client:
|
| 149 |
+
response = await client.get(self.auth_url, headers=headers, timeout=10.0)
|
| 150 |
+
if response.status_code == 200:
|
| 151 |
+
data = response.json()
|
| 152 |
+
token = data.get("token", "")
|
| 153 |
+
if token:
|
| 154 |
+
logger.debug(f"成功获取访客令牌: {token[:20]}...")
|
| 155 |
+
return token
|
| 156 |
+
except Exception as e:
|
| 157 |
+
logger.warning(f"异步获取访客令牌失败: {e}")
|
| 158 |
+
|
| 159 |
+
# 使用备份令牌
|
| 160 |
+
logger.debug("使用备份令牌")
|
| 161 |
+
return settings.BACKUP_TOKEN
|
| 162 |
+
|
| 163 |
+
async def transform_request_in(self, request: Dict[str, Any]) -> Dict[str, Any]:
|
| 164 |
+
"""
|
| 165 |
+
转换OpenAI请求为z.ai格式
|
| 166 |
+
整合现有功能:模型映射、MCP服务器等
|
| 167 |
+
"""
|
| 168 |
+
# 获取认证令牌
|
| 169 |
+
token = await self.get_token()
|
| 170 |
+
|
| 171 |
+
# 确定请求的模型特性
|
| 172 |
+
requested_model = request.get("model", settings.PRIMARY_MODEL)
|
| 173 |
+
is_thinking = requested_model == settings.THINKING_MODEL or request.get("reasoning", False)
|
| 174 |
+
is_search = requested_model == settings.SEARCH_MODEL
|
| 175 |
+
is_air = requested_model == settings.AIR_MODEL
|
| 176 |
+
|
| 177 |
+
# 获取上游模型ID(使用模型映射)
|
| 178 |
+
upstream_model_id = self.model_mapping.get(requested_model, "0727-360B-API")
|
| 179 |
+
|
| 180 |
+
# 处理消息列表
|
| 181 |
+
messages = []
|
| 182 |
+
for orig_msg in request.get("messages", []):
|
| 183 |
+
msg = orig_msg.copy()
|
| 184 |
+
|
| 185 |
+
# 处理system角色转换
|
| 186 |
+
if msg.get("role") == "system":
|
| 187 |
+
msg["role"] = "user"
|
| 188 |
+
content = msg.get("content")
|
| 189 |
+
|
| 190 |
+
if isinstance(content, list):
|
| 191 |
+
msg["content"] = [
|
| 192 |
+
{"type": "text", "text": "This is a system command, you must enforce compliance."}
|
| 193 |
+
] + content
|
| 194 |
+
elif isinstance(content, str):
|
| 195 |
+
msg["content"] = f"This is a system command, you must enforce compliance.{content}"
|
| 196 |
+
|
| 197 |
+
# 处理user角色的图片内容
|
| 198 |
+
elif msg.get("role") == "user":
|
| 199 |
+
content = msg.get("content")
|
| 200 |
+
if isinstance(content, list):
|
| 201 |
+
new_content = []
|
| 202 |
+
for part in content:
|
| 203 |
+
# 处理图片URL(支持base64和http URL)
|
| 204 |
+
if (
|
| 205 |
+
part.get("type") == "image_url"
|
| 206 |
+
and part.get("image_url", {}).get("url")
|
| 207 |
+
and isinstance(part["image_url"]["url"], str)
|
| 208 |
+
):
|
| 209 |
+
# 直接传递图片内容
|
| 210 |
+
new_content.append(part)
|
| 211 |
+
else:
|
| 212 |
+
new_content.append(part)
|
| 213 |
+
msg["content"] = new_content
|
| 214 |
+
|
| 215 |
+
# 处理assistant消息中的reasoning_content(保留原有功能)
|
| 216 |
+
elif msg.get("role") == "assistant" and msg.get("reasoning_content"):
|
| 217 |
+
# 如果有reasoning_content,保留它
|
| 218 |
+
pass
|
| 219 |
+
|
| 220 |
+
messages.append(msg)
|
| 221 |
+
|
| 222 |
+
# 构建MCP服务器列表(保留原有功能)
|
| 223 |
+
mcp_servers = []
|
| 224 |
+
if is_search:
|
| 225 |
+
mcp_servers.append("deep-web-search")
|
| 226 |
+
|
| 227 |
+
# 构建上游请求体
|
| 228 |
+
body = {
|
| 229 |
+
"stream": True, # 总是使用流式
|
| 230 |
+
"model": upstream_model_id, # 使用映射后的模型ID
|
| 231 |
+
"messages": messages,
|
| 232 |
+
"params": {},
|
| 233 |
+
"features": {
|
| 234 |
+
"image_generation": False,
|
| 235 |
+
"web_search": is_search,
|
| 236 |
+
"auto_web_search": is_search,
|
| 237 |
+
"preview_mode": False,
|
| 238 |
+
"flags": [],
|
| 239 |
+
"features": [],
|
| 240 |
+
"enable_thinking": is_thinking,
|
| 241 |
+
},
|
| 242 |
+
"background_tasks": {
|
| 243 |
+
"title_generation": False,
|
| 244 |
+
"tags_generation": False,
|
| 245 |
+
},
|
| 246 |
+
"mcp_servers": mcp_servers, # 保留MCP服务器支持
|
| 247 |
+
"variables": {
|
| 248 |
+
"{{USER_NAME}}": "Guest",
|
| 249 |
+
"{{USER_LOCATION}}": "Unknown",
|
| 250 |
+
"{{CURRENT_DATETIME}}": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
|
| 251 |
+
"{{CURRENT_DATE}}": datetime.now().strftime("%Y-%m-%d"),
|
| 252 |
+
"{{CURRENT_TIME}}": datetime.now().strftime("%H:%M:%S"),
|
| 253 |
+
"{{CURRENT_WEEKDAY}}": datetime.now().strftime("%A"),
|
| 254 |
+
"{{CURRENT_TIMEZONE}}": "UTC",
|
| 255 |
+
"{{USER_LANGUAGE}}": "zh-CN",
|
| 256 |
+
},
|
| 257 |
+
"model_item": {},
|
| 258 |
+
"tool_servers": [], # 保留工具服务器字段
|
| 259 |
+
"chat_id": generate_uuid(),
|
| 260 |
+
"id": generate_uuid(),
|
| 261 |
+
}
|
| 262 |
+
|
| 263 |
+
# 处理工具支持
|
| 264 |
+
if settings.TOOL_SUPPORT and not is_thinking and request.get("tools"):
|
| 265 |
+
body["tools"] = request["tools"]
|
| 266 |
+
else:
|
| 267 |
+
body["tools"] = None
|
| 268 |
+
|
| 269 |
+
# 构建请求配置(使用动态headers)
|
| 270 |
+
chat_id = body["chat_id"]
|
| 271 |
+
dynamic_headers = get_dynamic_headers(chat_id)
|
| 272 |
+
|
| 273 |
+
config = {
|
| 274 |
+
"url": self.api_url,
|
| 275 |
+
"headers": {
|
| 276 |
+
**dynamic_headers, # 使用动态生成的headers
|
| 277 |
+
"Authorization": f"Bearer {token}",
|
| 278 |
+
"Cache-Control": "no-cache",
|
| 279 |
+
"Connection": "keep-alive",
|
| 280 |
+
"Pragma": "no-cache",
|
| 281 |
+
"Sec-Fetch-Dest": "empty",
|
| 282 |
+
"Sec-Fetch-Mode": "cors",
|
| 283 |
+
"Sec-Fetch-Site": "same-origin",
|
| 284 |
+
},
|
| 285 |
+
}
|
| 286 |
+
|
| 287 |
+
return {"body": body, "config": config}
|
| 288 |
+
|
| 289 |
+
async def transform_response_out(
|
| 290 |
+
self, response_stream: Generator, context: Dict[str, Any]
|
| 291 |
+
) -> Generator[str, None, None]:
|
| 292 |
+
"""
|
| 293 |
+
转换z.ai响应为OpenAI格式
|
| 294 |
+
支持流式和非流式输出
|
| 295 |
+
"""
|
| 296 |
+
is_stream = context.get("req", {}).get("body", {}).get("stream", True)
|
| 297 |
+
|
| 298 |
+
# 初始化结果对象(用于非流式)
|
| 299 |
+
result = {
|
| 300 |
+
"id": "",
|
| 301 |
+
"choices": [
|
| 302 |
+
{
|
| 303 |
+
"finish_reason": None,
|
| 304 |
+
"index": 0,
|
| 305 |
+
"message": {
|
| 306 |
+
"content": "",
|
| 307 |
+
"role": "assistant",
|
| 308 |
+
},
|
| 309 |
+
}
|
| 310 |
+
],
|
| 311 |
+
"created": int(time.time()),
|
| 312 |
+
"model": context.get("req", {}).get("body", {}).get("model", ""),
|
| 313 |
+
"object": "chat.completion",
|
| 314 |
+
"usage": {
|
| 315 |
+
"completion_tokens": 0,
|
| 316 |
+
"prompt_tokens": 0,
|
| 317 |
+
"total_tokens": 0,
|
| 318 |
+
},
|
| 319 |
+
}
|
| 320 |
+
|
| 321 |
+
# 状态变量
|
| 322 |
+
current_id = ""
|
| 323 |
+
current_model = context.get("req", {}).get("body", {}).get("model", "")
|
| 324 |
+
has_tool_call = False
|
| 325 |
+
tool_args = ""
|
| 326 |
+
tool_id = ""
|
| 327 |
+
tool_call_usage = None
|
| 328 |
+
content_index = 0
|
| 329 |
+
has_thinking = False
|
| 330 |
+
|
| 331 |
+
async for line in response_stream:
|
| 332 |
+
if not line.strip():
|
| 333 |
+
continue
|
| 334 |
+
|
| 335 |
+
if line.startswith("data:"):
|
| 336 |
+
chunk_str = line[5:].strip()
|
| 337 |
+
if not chunk_str:
|
| 338 |
+
continue
|
| 339 |
+
|
| 340 |
+
try:
|
| 341 |
+
chunk = json.loads(chunk_str)
|
| 342 |
+
|
| 343 |
+
if chunk.get("type") == "chat:completion":
|
| 344 |
+
data = chunk.get("data", {})
|
| 345 |
+
|
| 346 |
+
# 保存ID和模型信息
|
| 347 |
+
if data.get("id"):
|
| 348 |
+
current_id = data["id"]
|
| 349 |
+
if data.get("model"):
|
| 350 |
+
current_model = data["model"]
|
| 351 |
+
|
| 352 |
+
# 处理不同阶段
|
| 353 |
+
phase = data.get("phase")
|
| 354 |
+
|
| 355 |
+
if phase == "tool_call":
|
| 356 |
+
# 处理工具调用
|
| 357 |
+
if not has_tool_call:
|
| 358 |
+
has_tool_call = True
|
| 359 |
+
|
| 360 |
+
edit_content = data.get("edit_content", "")
|
| 361 |
+
if edit_content:
|
| 362 |
+
blocks = edit_content.split("<glm_block >")
|
| 363 |
+
|
| 364 |
+
for index, block in enumerate(blocks):
|
| 365 |
+
if "</glm_block>" not in block:
|
| 366 |
+
continue
|
| 367 |
+
|
| 368 |
+
if index == 0:
|
| 369 |
+
# 第一个块:截取到 "result" 之前
|
| 370 |
+
if '"result' in edit_content:
|
| 371 |
+
tool_args += edit_content[: edit_content.index('"result') - 3]
|
| 372 |
+
else:
|
| 373 |
+
# 后续块:处理完整的工具调用
|
| 374 |
+
if tool_id:
|
| 375 |
+
# 完成前一个工具调用
|
| 376 |
+
try:
|
| 377 |
+
tool_args += '"'
|
| 378 |
+
params = json.loads(tool_args)
|
| 379 |
+
|
| 380 |
+
if is_stream:
|
| 381 |
+
# 发送工具参数
|
| 382 |
+
yield self._create_tool_chunk(
|
| 383 |
+
tool_id, None, params, content_index, current_id, current_model
|
| 384 |
+
)
|
| 385 |
+
else:
|
| 386 |
+
# 更新结果对象
|
| 387 |
+
if "tool_calls" not in result["choices"][0]["message"]:
|
| 388 |
+
result["choices"][0]["message"]["tool_calls"] = []
|
| 389 |
+
result["choices"][0]["message"]["tool_calls"][-1]["function"][
|
| 390 |
+
"arguments"
|
| 391 |
+
] = json.dumps(params)
|
| 392 |
+
except Exception as e:
|
| 393 |
+
logger.debug(f"解析工具参数错误: {e}")
|
| 394 |
+
finally:
|
| 395 |
+
tool_args = ""
|
| 396 |
+
tool_id = ""
|
| 397 |
+
|
| 398 |
+
# 开始新的工具调用
|
| 399 |
+
content_index += 1
|
| 400 |
+
block_content = block[: block.index("</glm_block>")]
|
| 401 |
+
|
| 402 |
+
try:
|
| 403 |
+
tool_data = json.loads(block_content)
|
| 404 |
+
metadata = tool_data.get("data", {}).get("metadata", {})
|
| 405 |
+
tool_id = metadata.get("id")
|
| 406 |
+
tool_name = metadata.get("name")
|
| 407 |
+
|
| 408 |
+
# 开始累积参数
|
| 409 |
+
args_str = json.dumps(metadata.get("arguments", {}))
|
| 410 |
+
tool_args += args_str[:-1] # 去掉结束的 }
|
| 411 |
+
|
| 412 |
+
if is_stream:
|
| 413 |
+
# 发送工具开始
|
| 414 |
+
yield self._create_tool_chunk(
|
| 415 |
+
tool_id, tool_name, "", content_index, current_id, current_model
|
| 416 |
+
)
|
| 417 |
+
else:
|
| 418 |
+
# 添加到结果
|
| 419 |
+
if "tool_calls" not in result["choices"][0]["message"]:
|
| 420 |
+
result["choices"][0]["message"]["tool_calls"] = []
|
| 421 |
+
result["choices"][0]["message"]["tool_calls"].append(
|
| 422 |
+
{
|
| 423 |
+
"id": tool_id,
|
| 424 |
+
"type": "function",
|
| 425 |
+
"function": {"name": tool_name, "arguments": ""},
|
| 426 |
+
}
|
| 427 |
+
)
|
| 428 |
+
except Exception as e:
|
| 429 |
+
logger.debug(f"解析工具块错误: {e}")
|
| 430 |
+
|
| 431 |
+
elif phase == "other":
|
| 432 |
+
# 处理其他阶段
|
| 433 |
+
if has_tool_call and data.get("usage"):
|
| 434 |
+
tool_call_usage = data["usage"]
|
| 435 |
+
|
| 436 |
+
edit_content = data.get("edit_content", "")
|
| 437 |
+
if has_tool_call and edit_content and edit_content.startswith("null,"):
|
| 438 |
+
# 工具调用结束
|
| 439 |
+
tool_args += '"'
|
| 440 |
+
has_tool_call = False
|
| 441 |
+
|
| 442 |
+
try:
|
| 443 |
+
params = json.loads(tool_args)
|
| 444 |
+
|
| 445 |
+
if is_stream:
|
| 446 |
+
# 发送最终参数和结束信号
|
| 447 |
+
yield self._create_tool_chunk(
|
| 448 |
+
tool_id, None, params, 0, current_id, current_model
|
| 449 |
+
)
|
| 450 |
+
|
| 451 |
+
# 发送完成信号
|
| 452 |
+
finish_chunk = {
|
| 453 |
+
"choices": [
|
| 454 |
+
{
|
| 455 |
+
"delta": {"role": "assistant", "content": None, "tool_calls": []},
|
| 456 |
+
"finish_reason": "tool_calls",
|
| 457 |
+
"index": 0,
|
| 458 |
+
"logprobs": None,
|
| 459 |
+
}
|
| 460 |
+
],
|
| 461 |
+
"created": int(time.time()),
|
| 462 |
+
"id": current_id,
|
| 463 |
+
"usage": tool_call_usage,
|
| 464 |
+
"model": current_model,
|
| 465 |
+
"object": "chat.completion.chunk",
|
| 466 |
+
"system_fingerprint": "fp_zai_001",
|
| 467 |
+
}
|
| 468 |
+
yield f"data: {json.dumps(finish_chunk)}\n\n"
|
| 469 |
+
yield "data: [DONE]\n\n"
|
| 470 |
+
else:
|
| 471 |
+
# 更新结果
|
| 472 |
+
result["choices"][0]["message"]["tool_calls"][-1]["function"]["arguments"] = (
|
| 473 |
+
json.dumps(params)
|
| 474 |
+
)
|
| 475 |
+
result["usage"] = tool_call_usage
|
| 476 |
+
result["choices"][0]["finish_reason"] = "tool_calls"
|
| 477 |
+
|
| 478 |
+
return # 结束处理
|
| 479 |
+
except Exception as e:
|
| 480 |
+
logger.debug(f"处理工具结束错误: {e}")
|
| 481 |
+
|
| 482 |
+
elif phase == "thinking":
|
| 483 |
+
# 处理思考阶段
|
| 484 |
+
if not has_thinking:
|
| 485 |
+
has_thinking = True
|
| 486 |
+
|
| 487 |
+
delta_content = data.get("delta_content", "")
|
| 488 |
+
if delta_content:
|
| 489 |
+
# 处理思考内容格式
|
| 490 |
+
if delta_content.startswith("<details"):
|
| 491 |
+
content = delta_content.split("</summary>\n>")[-1].strip()
|
| 492 |
+
else:
|
| 493 |
+
content = delta_content
|
| 494 |
+
|
| 495 |
+
if is_stream:
|
| 496 |
+
thinking_chunk = {
|
| 497 |
+
"choices": [
|
| 498 |
+
{
|
| 499 |
+
"delta": {"role": "assistant", "thinking": {"content": content}},
|
| 500 |
+
"finish_reason": None,
|
| 501 |
+
"index": 0,
|
| 502 |
+
"logprobs": None,
|
| 503 |
+
}
|
| 504 |
+
],
|
| 505 |
+
"created": int(time.time()),
|
| 506 |
+
"id": current_id,
|
| 507 |
+
"model": current_model,
|
| 508 |
+
"object": "chat.completion.chunk",
|
| 509 |
+
"system_fingerprint": "fp_zai_001",
|
| 510 |
+
}
|
| 511 |
+
yield f"data: {json.dumps(thinking_chunk)}\n\n"
|
| 512 |
+
else:
|
| 513 |
+
if "thinking" not in result["choices"][0]["message"]:
|
| 514 |
+
result["choices"][0]["message"]["thinking"] = {"content": ""}
|
| 515 |
+
result["choices"][0]["message"]["thinking"]["content"] += content
|
| 516 |
+
|
| 517 |
+
elif phase == "answer" and not has_tool_call:
|
| 518 |
+
# 处理答案阶段
|
| 519 |
+
edit_content = data.get("edit_content", "")
|
| 520 |
+
delta_content = data.get("delta_content", "")
|
| 521 |
+
|
| 522 |
+
# 处理思考结束和答案开始
|
| 523 |
+
if edit_content and "</details>\n" in edit_content:
|
| 524 |
+
if has_thinking:
|
| 525 |
+
signature = str(int(time.time() * 1000))
|
| 526 |
+
|
| 527 |
+
if is_stream:
|
| 528 |
+
# 发送思考签名
|
| 529 |
+
sig_chunk = {
|
| 530 |
+
"choices": [
|
| 531 |
+
{
|
| 532 |
+
"delta": {
|
| 533 |
+
"role": "assistant",
|
| 534 |
+
"thinking": {"content": "", "signature": signature},
|
| 535 |
+
},
|
| 536 |
+
"finish_reason": None,
|
| 537 |
+
"index": 0,
|
| 538 |
+
"logprobs": None,
|
| 539 |
+
}
|
| 540 |
+
],
|
| 541 |
+
"created": int(time.time()),
|
| 542 |
+
"id": current_id,
|
| 543 |
+
"model": current_model,
|
| 544 |
+
"object": "chat.completion.chunk",
|
| 545 |
+
"system_fingerprint": "fp_zai_001",
|
| 546 |
+
}
|
| 547 |
+
yield f"data: {json.dumps(sig_chunk)}\n\n"
|
| 548 |
+
content_index += 1
|
| 549 |
+
else:
|
| 550 |
+
result["choices"][0]["message"]["thinking"]["signature"] = signature
|
| 551 |
+
|
| 552 |
+
# 提取答案内容
|
| 553 |
+
content = edit_content.split("</details>\n")[-1]
|
| 554 |
+
if content:
|
| 555 |
+
if is_stream:
|
| 556 |
+
content_chunk = self._create_content_chunk(content, current_id, current_model)
|
| 557 |
+
yield f"data: {json.dumps(content_chunk)}\n\n"
|
| 558 |
+
else:
|
| 559 |
+
result["choices"][0]["message"]["content"] += content
|
| 560 |
+
|
| 561 |
+
# 处理增量内容
|
| 562 |
+
if delta_content:
|
| 563 |
+
if is_stream:
|
| 564 |
+
content_chunk = self._create_content_chunk(delta_content, current_id, current_model)
|
| 565 |
+
yield f"data: {json.dumps(content_chunk)}\n\n"
|
| 566 |
+
else:
|
| 567 |
+
result["choices"][0]["message"]["content"] += delta_content
|
| 568 |
+
|
| 569 |
+
# 处理完成
|
| 570 |
+
if data.get("usage") and not has_tool_call:
|
| 571 |
+
if is_stream:
|
| 572 |
+
# 发送完成信号
|
| 573 |
+
finish_chunk = {
|
| 574 |
+
"choices": [
|
| 575 |
+
{
|
| 576 |
+
"delta": {"role": "assistant", "content": ""},
|
| 577 |
+
"finish_reason": "stop",
|
| 578 |
+
"index": 0,
|
| 579 |
+
"logprobs": None,
|
| 580 |
+
}
|
| 581 |
+
],
|
| 582 |
+
"usage": data["usage"],
|
| 583 |
+
"created": int(time.time()),
|
| 584 |
+
"id": current_id,
|
| 585 |
+
"model": current_model,
|
| 586 |
+
"object": "chat.completion.chunk",
|
| 587 |
+
"system_fingerprint": "fp_zai_001",
|
| 588 |
+
}
|
| 589 |
+
yield f"data: {json.dumps(finish_chunk)}\n\n"
|
| 590 |
+
yield "data: [DONE]\n\n"
|
| 591 |
+
else:
|
| 592 |
+
result["choices"][0]["finish_reason"] = "stop"
|
| 593 |
+
result["usage"] = data["usage"]
|
| 594 |
+
|
| 595 |
+
except json.JSONDecodeError as e:
|
| 596 |
+
logger.error(f"JSON解析错误: {e}, 内容: {chunk_str[:100]}")
|
| 597 |
+
except Exception as e:
|
| 598 |
+
logger.error(f"处理响应块错误: {e}")
|
| 599 |
+
|
| 600 |
+
# 如果是非流式,返回最终结果
|
| 601 |
+
if not is_stream:
|
| 602 |
+
yield json.dumps(result)
|
| 603 |
+
|
| 604 |
+
def _create_content_chunk(self, content: str, chat_id: str, model: str) -> dict:
|
| 605 |
+
"""创建内容块(辅助函数)"""
|
| 606 |
+
return {
|
| 607 |
+
"choices": [
|
| 608 |
+
{
|
| 609 |
+
"delta": {"role": "assistant", "content": content},
|
| 610 |
+
"finish_reason": None,
|
| 611 |
+
"index": 0,
|
| 612 |
+
"logprobs": None,
|
| 613 |
+
}
|
| 614 |
+
],
|
| 615 |
+
"created": int(time.time()),
|
| 616 |
+
"id": chat_id,
|
| 617 |
+
"model": model,
|
| 618 |
+
"object": "chat.completion.chunk",
|
| 619 |
+
"system_fingerprint": "fp_zai_001",
|
| 620 |
+
}
|
| 621 |
+
|
| 622 |
+
def _create_tool_chunk(
|
| 623 |
+
self, tool_id: str, tool_name: Optional[str], arguments: Any, index: int, chat_id: str, model: str
|
| 624 |
+
) -> str:
|
| 625 |
+
"""创建工具调用块(辅助函数)"""
|
| 626 |
+
tool_delta = {
|
| 627 |
+
"id": tool_id,
|
| 628 |
+
"type": "function",
|
| 629 |
+
"function": {"name": tool_name, "arguments": json.dumps(arguments) if arguments else ""},
|
| 630 |
+
}
|
| 631 |
+
|
| 632 |
+
chunk = {
|
| 633 |
+
"choices": [
|
| 634 |
+
{
|
| 635 |
+
"delta": {"role": "assistant", "content": None, "tool_calls": [tool_delta]},
|
| 636 |
+
"finish_reason": None,
|
| 637 |
+
"index": index,
|
| 638 |
+
"logprobs": None,
|
| 639 |
+
}
|
| 640 |
+
],
|
| 641 |
+
"created": int(time.time()),
|
| 642 |
+
"id": chat_id,
|
| 643 |
+
"model": model,
|
| 644 |
+
"object": "chat.completion.chunk",
|
| 645 |
+
"system_fingerprint": "fp_zai_001",
|
| 646 |
+
}
|
| 647 |
+
|
| 648 |
+
return f"data: {json.dumps(chunk)}\n\n"
|
app/models/__init__.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 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 |
-
|
| 3 |
-
"""
|
| 4 |
|
| 5 |
from typing import Dict, List, Optional, Any, Union, Literal
|
| 6 |
from pydantic import BaseModel
|
|
@@ -54,8 +53,9 @@ 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[
|
| 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 |
tool_servers: Optional[List[str]] = None
|
| 58 |
+
tools: Optional[List[Dict[str, Any]]] = None # Add tools field for OpenAI compatibility
|
| 59 |
variables: Optional[Dict[str, str]] = None
|
| 60 |
model_config = {"protected_namespaces": ()}
|
| 61 |
|
app/utils/__init__.py
CHANGED
|
@@ -1,7 +1,6 @@
|
|
| 1 |
-
|
| 2 |
-
|
| 3 |
-
"""
|
| 4 |
|
| 5 |
-
from app.utils import
|
| 6 |
|
| 7 |
-
__all__ = ["
|
|
|
|
| 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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 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 |
+
log_path = Path(log_dir)
|
| 30 |
+
log_path.mkdir(parents=True, exist_ok=True)
|
| 31 |
+
|
| 32 |
+
console_format = (
|
| 33 |
+
"<green>{time:HH:mm:ss}</green> | <level>{level: <8}</level> | <level>{message}</level>"
|
| 34 |
+
if not debug_mode
|
| 35 |
+
else "<green>{time:YYYY-MM-DD HH:mm:ss}</green> | <level>{level: <8}</level> | "
|
| 36 |
+
"<cyan>{name}</cyan>:<cyan>{function}</cyan>:<cyan>{line}</cyan> | <level>{message}</level>"
|
| 37 |
+
)
|
| 38 |
+
|
| 39 |
+
logger.add(sys.stderr, level=log_level, format=console_format, colorize=True)
|
| 40 |
+
|
| 41 |
+
log_file = log_path / "{time:YYYY-MM-DD}.log"
|
| 42 |
+
file_format = "{time:YYYY-MM-DD HH:mm:ss.SSS} | {level: <8} | {name}:{function}:{line} | {message}"
|
| 43 |
+
|
| 44 |
+
logger.add(
|
| 45 |
+
str(log_file),
|
| 46 |
+
level=log_level,
|
| 47 |
+
format=file_format,
|
| 48 |
+
rotation=log_rotation,
|
| 49 |
+
retention=f"{log_retention_days} days",
|
| 50 |
+
encoding="utf-8",
|
| 51 |
+
compression="zip",
|
| 52 |
+
enqueue=True,
|
| 53 |
+
catch=True,
|
| 54 |
+
)
|
| 55 |
+
|
| 56 |
+
app_logger = logger
|
| 57 |
+
|
| 58 |
+
return logger
|
| 59 |
+
|
| 60 |
+
except Exception as e:
|
| 61 |
+
logger.remove()
|
| 62 |
+
logger.add(sys.stderr, level="ERROR")
|
| 63 |
+
logger.error(f"日志系统配置失败: {e}")
|
| 64 |
+
raise
|
| 65 |
+
|
| 66 |
+
|
| 67 |
+
def get_logger():
|
| 68 |
+
"""Get the logger instance"""
|
| 69 |
+
global app_logger
|
| 70 |
+
if app_logger is None:
|
| 71 |
+
|
| 72 |
+
app_logger = logger
|
| 73 |
+
logger.add(sys.stderr, level="INFO")
|
| 74 |
+
return app_logger
|
| 75 |
+
|
| 76 |
+
|
| 77 |
+
if __name__ == "__main__":
|
| 78 |
+
"""Test the logger"""
|
| 79 |
+
import tempfile
|
| 80 |
+
|
| 81 |
+
with tempfile.TemporaryDirectory() as temp_dir:
|
| 82 |
+
try:
|
| 83 |
+
setup_logger(temp_dir, debug_mode=True)
|
| 84 |
+
|
| 85 |
+
logger.debug("这是一条调试日志")
|
| 86 |
+
logger.info("这是一条信息日志")
|
| 87 |
+
logger.warning("这是一条警告日志")
|
| 88 |
+
logger.error("这是一条错误日志")
|
| 89 |
+
logger.critical("这是一条严重日志")
|
| 90 |
+
|
| 91 |
+
try:
|
| 92 |
+
1 / 0
|
| 93 |
+
except ZeroDivisionError:
|
| 94 |
+
logger.exception("发生了除零异常")
|
| 95 |
+
|
| 96 |
+
print("✅ 日志测试完成")
|
| 97 |
+
|
| 98 |
+
logger.remove()
|
| 99 |
+
|
| 100 |
+
except Exception as e:
|
| 101 |
+
print(f"❌ 日志测试失败: {e}")
|
| 102 |
+
logger.remove()
|
| 103 |
+
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()
|
|
|
|
|
|
|
|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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
#!/usr/bin/env python
|
| 2 |
+
# -*- coding: utf-8 -*-
|
| 3 |
+
|
| 4 |
+
"""
|
| 5 |
+
SSE Tool Handler - 处理工具调用的SSE流
|
| 6 |
+
实现glm_block分割和工具参数累积逻辑
|
| 7 |
+
"""
|
| 8 |
+
|
| 9 |
+
import json
|
| 10 |
+
import time
|
| 11 |
+
import uuid
|
| 12 |
+
from typing import Dict, Any, Optional, Generator, List
|
| 13 |
+
from dataclasses import dataclass, field
|
| 14 |
+
|
| 15 |
+
from app.utils.logger import get_logger
|
| 16 |
+
|
| 17 |
+
logger = get_logger()
|
| 18 |
+
|
| 19 |
+
|
| 20 |
+
@dataclass
|
| 21 |
+
class ToolCallState:
|
| 22 |
+
"""工具调用状态管理"""
|
| 23 |
+
|
| 24 |
+
has_tool_call: bool = False
|
| 25 |
+
tool_args: str = ""
|
| 26 |
+
tool_id: str = ""
|
| 27 |
+
tool_name: str = ""
|
| 28 |
+
tool_calls: List[Dict] = field(default_factory=list)
|
| 29 |
+
tool_call_index: int = 0
|
| 30 |
+
tool_call_usage: Optional[Dict] = None
|
| 31 |
+
tool_call_buffer: str = "" # 累积buffer用于处理分割的内容
|
| 32 |
+
is_first_block: bool = True # 是否是第一个块
|
| 33 |
+
|
| 34 |
+
|
| 35 |
+
class SSEToolHandler:
|
| 36 |
+
"""
|
| 37 |
+
SSE工具处理器 - 实现工具调用逻辑
|
| 38 |
+
包含glm_block分割解析和参数累积机制
|
| 39 |
+
"""
|
| 40 |
+
|
| 41 |
+
def __init__(self, chat_id: str, model: str):
|
| 42 |
+
self.chat_id = chat_id
|
| 43 |
+
self.model = model
|
| 44 |
+
self.state = ToolCallState()
|
| 45 |
+
self.has_thinking = False
|
| 46 |
+
self.content_index = 0
|
| 47 |
+
|
| 48 |
+
def process_tool_call_phase(self, data: Dict[str, Any], is_stream: bool = True) -> Generator[str, None, None]:
|
| 49 |
+
"""
|
| 50 |
+
处理tool_call阶段
|
| 51 |
+
"""
|
| 52 |
+
if not self.state.has_tool_call:
|
| 53 |
+
self.state.has_tool_call = True
|
| 54 |
+
logger.debug("进入工具调用阶段")
|
| 55 |
+
|
| 56 |
+
edit_content = data.get("edit_content", "")
|
| 57 |
+
if not edit_content:
|
| 58 |
+
return
|
| 59 |
+
|
| 60 |
+
# 分割glm_block块
|
| 61 |
+
blocks = edit_content.split("<glm_block >")
|
| 62 |
+
|
| 63 |
+
for index, block in enumerate(blocks):
|
| 64 |
+
if not block or "</glm_block>" not in block:
|
| 65 |
+
continue
|
| 66 |
+
|
| 67 |
+
if index == 0:
|
| 68 |
+
# 第一个块:提取到"result"之前的内容作为参数片段
|
| 69 |
+
if '"result"' in edit_content:
|
| 70 |
+
# 提取到result之前的内容(去掉", "result")
|
| 71 |
+
args_fragment = edit_content[: edit_content.index('"result"') - 3]
|
| 72 |
+
self.state.tool_args += args_fragment
|
| 73 |
+
logger.debug(f"从第一个块提取参数片段: {args_fragment}")
|
| 74 |
+
else:
|
| 75 |
+
# 如果没有result字段,这是一个分片的参数
|
| 76 |
+
# 提取到</glm_block>之前的所有内容(但不包括</glm_block>)
|
| 77 |
+
if "</glm_block>" in block:
|
| 78 |
+
end_idx = block.index("</glm_block>")
|
| 79 |
+
args_fragment = block[:end_idx]
|
| 80 |
+
else:
|
| 81 |
+
args_fragment = block
|
| 82 |
+
|
| 83 |
+
# 直接累积参数片段,不做修改
|
| 84 |
+
self.state.tool_args += args_fragment
|
| 85 |
+
logger.debug(f"累积参数片段: {args_fragment}")
|
| 86 |
+
else:
|
| 87 |
+
# 后续块:包含工具元数据
|
| 88 |
+
try:
|
| 89 |
+
# 提取块内容(去掉</glm_block>)
|
| 90 |
+
block_content = block[: block.index("</glm_block>")]
|
| 91 |
+
content = json.loads(block_content)
|
| 92 |
+
metadata = content.get("data", {}).get("metadata", {})
|
| 93 |
+
|
| 94 |
+
# 新工具调用
|
| 95 |
+
tool_id = metadata.get("id", "")
|
| 96 |
+
tool_name = metadata.get("name", "")
|
| 97 |
+
arguments = metadata.get("arguments", {})
|
| 98 |
+
|
| 99 |
+
if tool_id and tool_id != self.state.tool_id:
|
| 100 |
+
# 如果有前一个工具调用未完成,先完成它
|
| 101 |
+
if self.state.tool_id and self.state.tool_args:
|
| 102 |
+
# 补充最后的引号
|
| 103 |
+
if not self.state.tool_args.endswith("}"):
|
| 104 |
+
self.state.tool_args += '"'
|
| 105 |
+
yield from self._complete_tool_call(is_stream)
|
| 106 |
+
|
| 107 |
+
# 保存新工具信息s
|
| 108 |
+
self.state.tool_id = tool_id
|
| 109 |
+
self.state.tool_name = tool_name
|
| 110 |
+
# 开始新的参数累积(去掉最后的}以便后续累积)
|
| 111 |
+
self.state.tool_args = json.dumps(arguments, ensure_ascii=False)[:-1]
|
| 112 |
+
|
| 113 |
+
logger.debug(f"新工具调用: {tool_name}(id={tool_id})")
|
| 114 |
+
logger.debug(f"初始参数: {self.state.tool_args}")
|
| 115 |
+
|
| 116 |
+
if is_stream:
|
| 117 |
+
yield self._create_tool_start_chunk()
|
| 118 |
+
|
| 119 |
+
self.content_index += 1
|
| 120 |
+
|
| 121 |
+
except (json.JSONDecodeError, KeyError) as e:
|
| 122 |
+
logger.error(f"解析工具块失败: {e}, block: {block_content}")
|
| 123 |
+
|
| 124 |
+
# 检查参数是否完整
|
| 125 |
+
if self.state.tool_args:
|
| 126 |
+
try:
|
| 127 |
+
# 尝试补充}并解析
|
| 128 |
+
test_args = (
|
| 129 |
+
self.state.tool_args + "}" if not self.state.tool_args.endswith("}") else self.state.tool_args
|
| 130 |
+
)
|
| 131 |
+
json.loads(test_args)
|
| 132 |
+
self.state.tool_args_complete = True
|
| 133 |
+
logger.debug(f"参数完整: {test_args}")
|
| 134 |
+
except json.JSONDecodeError:
|
| 135 |
+
logger.debug(f"参数未完整,当前长度: {len(self.state.tool_args)}")
|
| 136 |
+
|
| 137 |
+
def _complete_tool_call(self, is_stream: bool) -> Generator[str, None, None]:
|
| 138 |
+
"""完成当前工具调用"""
|
| 139 |
+
try:
|
| 140 |
+
# 尝试解析参数
|
| 141 |
+
# 参数应该已经在process_other_phase中补充完整
|
| 142 |
+
params = None
|
| 143 |
+
|
| 144 |
+
try:
|
| 145 |
+
params = json.loads(self.state.tool_args)
|
| 146 |
+
logger.debug(f"参数解析成功: {json.dumps(params, ensure_ascii=False)[:100]}")
|
| 147 |
+
except json.JSONDecodeError as e:
|
| 148 |
+
logger.error(f"解析失败: {e}")
|
| 149 |
+
logger.error(f"原始参数: {self.state.tool_args[:200]}")
|
| 150 |
+
# 使用空参数
|
| 151 |
+
params = {}
|
| 152 |
+
|
| 153 |
+
logger.debug(f"完成工具调用: {self.state.tool_name} with params: {params}")
|
| 154 |
+
|
| 155 |
+
if is_stream:
|
| 156 |
+
# 发送参数
|
| 157 |
+
yield self._create_tool_arguments_chunk(params)
|
| 158 |
+
|
| 159 |
+
except Exception as e:
|
| 160 |
+
logger.error(f"处理工具参数异常: {e}")
|
| 161 |
+
finally:
|
| 162 |
+
# 重置状态
|
| 163 |
+
self.state.tool_args = ""
|
| 164 |
+
self.state.tool_id = ""
|
| 165 |
+
self.state.tool_name = ""
|
| 166 |
+
self.state.tool_args_complete = False
|
| 167 |
+
|
| 168 |
+
def process_other_phase(self, data: Dict[str, Any], is_stream: bool = True) -> Generator[str, None, None]:
|
| 169 |
+
"""
|
| 170 |
+
处理other阶段
|
| 171 |
+
主要处理工具调用的结束
|
| 172 |
+
"""
|
| 173 |
+
edit_content = data.get("edit_content", "")
|
| 174 |
+
usage = data.get("usage")
|
| 175 |
+
|
| 176 |
+
# 保存usage(如果在工具调用模式)
|
| 177 |
+
if self.state.has_tool_call and usage:
|
| 178 |
+
self.state.tool_call_usage = usage
|
| 179 |
+
logger.debug(f"保存工具调用usage: {usage}")
|
| 180 |
+
|
| 181 |
+
# 检查工具调用结束标记
|
| 182 |
+
if self.state.has_tool_call and edit_content and edit_content.startswith("null,"):
|
| 183 |
+
logger.debug("检测到工具调用结束标记: null,")
|
| 184 |
+
|
| 185 |
+
# 如果有未完成的工具调用,完成它
|
| 186 |
+
if self.state.tool_id and self.state.tool_args:
|
| 187 |
+
# 补充结束引号
|
| 188 |
+
self.state.tool_args += '"'
|
| 189 |
+
|
| 190 |
+
logger.debug(f"准备完成工具调用,当前参数: {self.state.tool_args}")
|
| 191 |
+
yield from self._complete_tool_call(is_stream)
|
| 192 |
+
|
| 193 |
+
# 发送完成信号
|
| 194 |
+
if is_stream:
|
| 195 |
+
yield self._create_tool_finish_chunk()
|
| 196 |
+
yield "data: [DONE]\n\n"
|
| 197 |
+
|
| 198 |
+
# 重置所有状态
|
| 199 |
+
self.state.has_tool_call = False
|
| 200 |
+
self.state.tool_call_usage = None
|
| 201 |
+
self.state.tool_call_buffer = ""
|
| 202 |
+
self.state.tool_args = ""
|
| 203 |
+
self.state.tool_id = ""
|
| 204 |
+
self.state.tool_name = ""
|
| 205 |
+
self.state.tool_args_complete = False
|
| 206 |
+
self.state.is_first_block = True
|
| 207 |
+
|
| 208 |
+
def _create_tool_start_chunk(self) -> str:
|
| 209 |
+
"""创建工具调用开始的chunk"""
|
| 210 |
+
chunk = {
|
| 211 |
+
"choices": [
|
| 212 |
+
{
|
| 213 |
+
"delta": {
|
| 214 |
+
"role": "assistant",
|
| 215 |
+
"content": None,
|
| 216 |
+
"tool_calls": [
|
| 217 |
+
{
|
| 218 |
+
"id": self.state.tool_id,
|
| 219 |
+
"type": "function",
|
| 220 |
+
"function": {"name": self.state.tool_name, "arguments": ""},
|
| 221 |
+
}
|
| 222 |
+
],
|
| 223 |
+
},
|
| 224 |
+
"finish_reason": None,
|
| 225 |
+
"index": self.content_index,
|
| 226 |
+
"logprobs": None,
|
| 227 |
+
}
|
| 228 |
+
],
|
| 229 |
+
"created": int(time.time()),
|
| 230 |
+
"id": self.chat_id,
|
| 231 |
+
"model": self.model,
|
| 232 |
+
"object": "chat.completion.chunk",
|
| 233 |
+
"system_fingerprint": "fp_zai_001",
|
| 234 |
+
}
|
| 235 |
+
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 236 |
+
|
| 237 |
+
def _create_tool_arguments_chunk(self, arguments: Dict) -> str:
|
| 238 |
+
"""创建工具参数的chunk"""
|
| 239 |
+
chunk = {
|
| 240 |
+
"choices": [
|
| 241 |
+
{
|
| 242 |
+
"delta": {
|
| 243 |
+
"role": "assistant",
|
| 244 |
+
"content": None,
|
| 245 |
+
"tool_calls": [
|
| 246 |
+
{
|
| 247 |
+
"id": self.state.tool_id,
|
| 248 |
+
"type": "function",
|
| 249 |
+
"function": {"name": None, "arguments": json.dumps(arguments, ensure_ascii=False)},
|
| 250 |
+
}
|
| 251 |
+
],
|
| 252 |
+
},
|
| 253 |
+
"finish_reason": None,
|
| 254 |
+
"index": 0,
|
| 255 |
+
"logprobs": None,
|
| 256 |
+
}
|
| 257 |
+
],
|
| 258 |
+
"created": int(time.time()),
|
| 259 |
+
"id": self.chat_id,
|
| 260 |
+
"model": self.model,
|
| 261 |
+
"object": "chat.completion.chunk",
|
| 262 |
+
"system_fingerprint": "fp_zai_001",
|
| 263 |
+
}
|
| 264 |
+
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
| 265 |
+
|
| 266 |
+
def _create_tool_finish_chunk(self) -> str:
|
| 267 |
+
"""创建工具调用完成的chunk"""
|
| 268 |
+
chunk = {
|
| 269 |
+
"choices": [
|
| 270 |
+
{
|
| 271 |
+
"delta": {"role": "assistant", "content": None, "tool_calls": []},
|
| 272 |
+
"finish_reason": "tool_calls",
|
| 273 |
+
"index": 0,
|
| 274 |
+
"logprobs": None,
|
| 275 |
+
}
|
| 276 |
+
],
|
| 277 |
+
"created": int(time.time()),
|
| 278 |
+
"id": self.chat_id,
|
| 279 |
+
"usage": self.state.tool_call_usage,
|
| 280 |
+
"model": self.model,
|
| 281 |
+
"object": "chat.completion.chunk",
|
| 282 |
+
"system_fingerprint": "fp_zai_001",
|
| 283 |
+
}
|
| 284 |
+
return f"data: {json.dumps(chunk, ensure_ascii=False)}\n\n"
|
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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|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
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
main.py
CHANGED
|
@@ -1,19 +1,20 @@
|
|
| 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",
|
|
@@ -52,7 +53,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 fastapi import FastAPI, Request, Response
|
| 5 |
from fastapi.middleware.cors import CORSMiddleware
|
| 6 |
|
| 7 |
from app.core.config import settings
|
| 8 |
from app.core import openai
|
| 9 |
from app.utils.reload_config import RELOAD_CONFIG
|
| 10 |
+
from app.utils.logger import setup_logger
|
| 11 |
|
| 12 |
from granian import Granian
|
| 13 |
|
| 14 |
+
|
| 15 |
+
# Setup logger
|
| 16 |
+
logger = setup_logger(log_dir="logs", debug_mode=settings.DEBUG_LOGGING)
|
| 17 |
+
|
| 18 |
# Create FastAPI app
|
| 19 |
app = FastAPI(
|
| 20 |
title="OpenAI Compatible API Server",
|
|
|
|
| 53 |
interface="asgi",
|
| 54 |
address="0.0.0.0",
|
| 55 |
port=settings.LISTEN_PORT,
|
| 56 |
+
reload=False, # 生产环境请关闭热重载
|
| 57 |
**RELOAD_CONFIG,
|
| 58 |
).serve()
|
| 59 |
|
pyproject.toml
CHANGED
|
@@ -32,6 +32,7 @@ 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 |
]
|
| 37 |
|
| 38 |
[project.scripts]
|
requirements.txt
CHANGED
|
@@ -5,4 +5,5 @@ 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
|
|
|
|
|
|
| 5 |
pydantic-settings==2.10.1
|
| 6 |
pydantic-core==2.33.2
|
| 7 |
typing-inspection==0.4.1
|
| 8 |
+
fake-useragent==2.2.0
|
| 9 |
+
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 |
-
|
| 25 |
-
|
| 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()
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|