File size: 12,410 Bytes
24926a5 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 | import asyncio
import json
import time
import random
from typing import Any, AsyncGenerator, Callable
from asyncio import Event
from playwright.async_api import Page as AsyncPage
from models import ClientDisconnectedError, ChatCompletionRequest
from config import CHAT_COMPLETION_ID_PREFIX
from .utils import use_stream_response, calculate_usage_stats, generate_sse_chunk, generate_sse_stop_chunk
from .common_utils import random_id
async def gen_sse_from_aux_stream(
req_id: str,
request: ChatCompletionRequest,
model_name_for_stream: str,
check_client_disconnected: Callable,
event_to_set: Event,
) -> AsyncGenerator[str, None]:
"""辅助流队列 -> OpenAI 兼容 SSE 生成器。
产出增量、tool_calls、最终 usage 与 [DONE]。
"""
from server import logger
last_reason_pos = 0
last_body_pos = 0
chat_completion_id = f"{CHAT_COMPLETION_ID_PREFIX}{req_id}-{int(time.time())}-{random.randint(100, 999)}"
created_timestamp = int(time.time())
full_reasoning_content = ""
full_body_content = ""
data_receiving = False
try:
async for raw_data in use_stream_response(req_id):
data_receiving = True
try:
check_client_disconnected(f"流式生成器循环 ({req_id}): ")
except ClientDisconnectedError:
logger.info(f"[{req_id}] 客户端断开连接,终止流式生成")
if data_receiving and not event_to_set.is_set():
logger.info(f"[{req_id}] 数据接收中客户端断开,立即设置done信号")
event_to_set.set()
break
if isinstance(raw_data, str):
try:
data = json.loads(raw_data)
except json.JSONDecodeError:
logger.warning(f"[{req_id}] 无法解析流数据JSON: {raw_data}")
continue
elif isinstance(raw_data, dict):
data = raw_data
else:
logger.warning(f"[{req_id}] 未知的流数据类型: {type(raw_data)}")
continue
if not isinstance(data, dict):
logger.warning(f"[{req_id}] 数据不是字典类型: {data}")
continue
reason = data.get("reason", "")
body = data.get("body", "")
done = data.get("done", False)
function = data.get("function", [])
if reason:
full_reasoning_content = reason
if body:
full_body_content = body
if len(reason) > last_reason_pos:
output = {
"id": chat_completion_id,
"object": "chat.completion.chunk",
"model": model_name_for_stream,
"created": created_timestamp,
"choices": [{
"index": 0,
"delta": {
"role": "assistant",
"content": None,
"reasoning_content": reason[last_reason_pos:],
},
"finish_reason": None,
"native_finish_reason": None,
}],
}
last_reason_pos = len(reason)
yield f"data: {json.dumps(output, ensure_ascii=False, separators=(',', ':'))}\n\n"
if len(body) > last_body_pos:
finish_reason_val = None
if done:
finish_reason_val = "stop"
delta_content = {"role": "assistant", "content": body[last_body_pos:]}
choice_item = {
"index": 0,
"delta": delta_content,
"finish_reason": finish_reason_val,
"native_finish_reason": finish_reason_val,
}
if done and function and len(function) > 0:
tool_calls_list = []
for func_idx, function_call_data in enumerate(function):
tool_calls_list.append({
"id": f"call_{random_id()}",
"index": func_idx,
"type": "function",
"function": {
"name": function_call_data["name"],
"arguments": json.dumps(function_call_data["params"]),
},
})
delta_content["tool_calls"] = tool_calls_list
choice_item["finish_reason"] = "tool_calls"
choice_item["native_finish_reason"] = "tool_calls"
delta_content["content"] = None
output = {
"id": chat_completion_id,
"object": "chat.completion.chunk",
"model": model_name_for_stream,
"created": created_timestamp,
"choices": [choice_item],
}
last_body_pos = len(body)
yield f"data: {json.dumps(output, ensure_ascii=False, separators=(',', ':'))}\n\n"
elif done:
if function and len(function) > 0:
tool_calls_list = []
for func_idx, function_call_data in enumerate(function):
tool_calls_list.append({
"id": f"call_{random_id()}",
"index": func_idx,
"type": "function",
"function": {
"name": function_call_data["name"],
"arguments": json.dumps(function_call_data["params"]),
},
})
delta_content = {"role": "assistant", "content": None, "tool_calls": tool_calls_list}
choice_item = {
"index": 0,
"delta": delta_content,
"finish_reason": "tool_calls",
"native_finish_reason": "tool_calls",
}
else:
choice_item = {
"index": 0,
"delta": {"role": "assistant"},
"finish_reason": "stop",
"native_finish_reason": "stop",
}
output = {
"id": chat_completion_id,
"object": "chat.completion.chunk",
"model": model_name_for_stream,
"created": created_timestamp,
"choices": [choice_item],
}
yield f"data: {json.dumps(output, ensure_ascii=False, separators=(',', ':'))}\n\n"
except ClientDisconnectedError:
logger.info(f"[{req_id}] 流式生成器中检测到客户端断开连接")
if data_receiving and not event_to_set.is_set():
logger.info(f"[{req_id}] 客户端断开异常处理中立即设置done信号")
event_to_set.set()
except Exception as e:
logger.error(f"[{req_id}] 流式生成器处理过程中发生错误: {e}", exc_info=True)
try:
error_chunk = {
"id": chat_completion_id,
"object": "chat.completion.chunk",
"model": model_name_for_stream,
"created": created_timestamp,
"choices": [{
"index": 0,
"delta": {"role": "assistant", "content": f"\n\n[错误: {str(e)}]"},
"finish_reason": "stop",
"native_finish_reason": "stop",
}],
}
yield f"data: {json.dumps(error_chunk, ensure_ascii=False, separators=(',', ':'))}\n\n"
except Exception:
pass
finally:
try:
usage_stats = calculate_usage_stats(
[msg.model_dump() for msg in request.messages],
full_body_content,
full_reasoning_content,
)
logger.info(f"[{req_id}] 计算的token使用统计: {usage_stats}")
final_chunk = {
"id": chat_completion_id,
"object": "chat.completion.chunk",
"model": model_name_for_stream,
"created": created_timestamp,
"choices": [{
"index": 0,
"delta": {},
"finish_reason": "stop",
"native_finish_reason": "stop",
}],
"usage": usage_stats,
}
yield f"data: {json.dumps(final_chunk, ensure_ascii=False, separators=(',', ':'))}\n\n"
except Exception as usage_err:
logger.error(f"[{req_id}] 计算或发送usage统计时出错: {usage_err}")
try:
logger.info(f"[{req_id}] 流式生成器完成,发送 [DONE] 标记")
yield "data: [DONE]\n\n"
except Exception as done_err:
logger.error(f"[{req_id}] 发送 [DONE] 标记时出错: {done_err}")
if not event_to_set.is_set():
event_to_set.set()
logger.info(f"[{req_id}] 流式生成器完成事件已设置")
async def gen_sse_from_playwright(
page: AsyncPage,
logger: Any,
req_id: str,
model_name_for_stream: str,
request: ChatCompletionRequest,
check_client_disconnected: Callable,
completion_event: Event,
) -> AsyncGenerator[str, None]:
"""Playwright 最终响应 -> OpenAI 兼容 SSE 生成器。"""
# Reuse already-imported helpers from utils to avoid repeated imports
from models import ClientDisconnectedError
from browser_utils.page_controller import PageController
data_receiving = False
try:
page_controller = PageController(page, logger, req_id)
final_content = await page_controller.get_response(check_client_disconnected)
data_receiving = True
lines = final_content.split('\n')
for line_idx, line in enumerate(lines):
try:
check_client_disconnected(f"Playwright流式生成器循环 ({req_id}): ")
except ClientDisconnectedError:
logger.info(f"[{req_id}] Playwright流式生成器中检测到客户端断开连接")
if data_receiving and not completion_event.is_set():
logger.info(f"[{req_id}] Playwright数据接收中客户端断开,立即设置done信号")
completion_event.set()
break
if line:
chunk_size = 5
for i in range(0, len(line), chunk_size):
chunk = line[i:i+chunk_size]
yield generate_sse_chunk(chunk, req_id, model_name_for_stream)
await asyncio.sleep(0.03)
if line_idx < len(lines) - 1:
yield generate_sse_chunk('\n', req_id, model_name_for_stream)
await asyncio.sleep(0.01)
usage_stats = calculate_usage_stats(
[msg.model_dump() for msg in request.messages], final_content, "",
)
logger.info(f"[{req_id}] Playwright非流式计算的token使用统计: {usage_stats}")
yield generate_sse_stop_chunk(req_id, model_name_for_stream, "stop", usage_stats)
except ClientDisconnectedError:
logger.info(f"[{req_id}] Playwright流式生成器中检测到客户端断开连接")
if data_receiving and not completion_event.is_set():
logger.info(f"[{req_id}] Playwright客户端断开异常处理中立即设置done信号")
completion_event.set()
except Exception as e:
logger.error(f"[{req_id}] Playwright流式生成器处理过程中发生错误: {e}", exc_info=True)
try:
yield generate_sse_chunk(f"\n\n[错误: {str(e)}]", req_id, model_name_for_stream)
yield generate_sse_stop_chunk(req_id, model_name_for_stream)
except Exception:
pass
finally:
if not completion_event.is_set():
completion_event.set()
logger.info(f"[{req_id}] Playwright流式生成器完成事件已设置")
|