From 44a50d3d4d74ac18bfbb5092f9c7eda87404a4d0 Mon Sep 17 00:00:00 2001
From: pzy <2360718056@qq.com>
Date: Sun, 12 Apr 2026 17:26:45 +0800
Subject: [PATCH] =?UTF-8?q?feat:=20port=20=E6=9C=AC=E5=9C=B0=E8=87=AA?=
=?UTF-8?q?=E5=AE=9A=E4=B9=89=E8=A1=A5=E4=B8=81=E5=88=B0=E6=96=B0=E6=9E=B6?=
=?UTF-8?q?=E6=9E=84?=
MIME-Version: 1.0
Content-Type: text/plain; charset=UTF-8
Content-Transfer-Encoding: 8bit
上游大重构后以下本地补丁重新迁移到 app/products/openai 下:
- feat: 心跳机制 (_sse_with_heartbeat)
在 router.py 为 /v1/chat/completions 和 /v1/responses 的 SSE 响应
添加初始 2KB 填充 + 每 30s `: ping` 心跳,防反代/CDN 断连;
并在 _SSE_HEADERS 增加 X-Accel-Buffering: no。
- feat: remove_think_tags
chat.py._extract_message 清理消息中 ... 块和
内联 base64 图片(data:image/...;base64,...),避免把模型自己的
推理内容和超大图片重发给上游。
- feat: deepsearch_preset 透传
ChatCompletionRequest 新增 deepsearch 字段 (default/deeper),
router 转换为 request_overrides={deepsearchPreset: ...}
通过上游已有的 build_chat_payload request_overrides 链路透传。
- fix: 视频请求失败返回真实 HTTP 状态码
chat_completions_endpoint 在视频模型分支下异常直接 raise,
不再包装为 SSE 200,避免 New API 等计费网关误判为成功扣费。
---
app/products/openai/chat.py | 21 +++++++++--
app/products/openai/router.py | 65 ++++++++++++++++++++++++++++------
app/products/openai/schemas.py | 3 ++
3 files changed, 75 insertions(+), 14 deletions(-)
diff --git a/app/products/openai/chat.py b/app/products/openai/chat.py
index 5e5db437..67beb420 100644
--- a/app/products/openai/chat.py
+++ b/app/products/openai/chat.py
@@ -2,6 +2,7 @@
import asyncio
import base64
+import re
from typing import Any, AsyncGenerator
import orjson
@@ -188,6 +189,19 @@ def _normalize_image_format(value: str | None) -> str:
return fmt
+_THINK_TAG_RE = re.compile(r"[\s\S]*?")
+_INLINE_BASE64_IMG_RE = re.compile(r"!\[image\]\(data:[^)]*?base64,[^)]*?\)")
+
+
+def _strip_think_and_inline_images(text: str) -> str:
+ """Remove ... blocks and inline base64 images from text."""
+ if not text or not isinstance(text, str):
+ return text
+ text = _THINK_TAG_RE.sub("", text).strip()
+ text = _INLINE_BASE64_IMG_RE.sub("[图片]", text)
+ return text
+
+
def _extract_message(messages: list[dict]) -> tuple[str, list[str]]:
"""Flatten OpenAI messages into a single prompt string + file attachments."""
parts: list[str] = []
@@ -222,15 +236,16 @@ def _extract_message(messages: list[dict]) -> tuple[str, list[str]]:
# ── normal content handling ───────────────────────────────────────────
if isinstance(content, str):
- if content.strip():
- parts.append(f"[{role}]: {content.strip()}")
+ cleaned = _strip_think_and_inline_images(content.strip())
+ if cleaned:
+ parts.append(f"[{role}]: {cleaned}")
elif isinstance(content, list):
for block in content:
if not isinstance(block, dict):
continue
btype = block.get("type")
if btype == "text":
- text = (block.get("text") or "").strip()
+ text = _strip_think_and_inline_images((block.get("text") or "").strip())
if text:
parts.append(f"[{role}]: {text}")
elif btype == "image_url":
diff --git a/app/products/openai/router.py b/app/products/openai/router.py
index 9020b2f4..a48545a3 100644
--- a/app/products/openai/router.py
+++ b/app/products/openai/router.py
@@ -1,5 +1,6 @@
"""OpenAI-compatible API router (/v1/*)."""
+import asyncio
import base64
import binascii
import mimetypes
@@ -119,7 +120,36 @@ async def _safe_sse(stream: AsyncIterable[str]) -> AsyncGenerator[str, None]:
yield "data: [DONE]\n\n"
-_SSE_HEADERS = {"Cache-Control": "no-cache", "Connection": "keep-alive"}
+_SSE_HEADERS = {
+ "Cache-Control": "no-cache",
+ "Connection": "keep-alive",
+ "X-Accel-Buffering": "no",
+}
+
+_HEARTBEAT_INTERVAL_S = 30
+
+
+async def _sse_with_heartbeat(
+ stream: AsyncIterable[str], interval: int = _HEARTBEAT_INTERVAL_S
+) -> AsyncGenerator[str, None]:
+ """Keep SSE connections alive through reverse proxies / CDNs.
+
+ - Initial 2KB padding forces intermediate buffers (nginx, Cloudflare) to flush.
+ - `: ping` comments sent every `interval` seconds of silence.
+ """
+ yield ": heartbeat stream connected\n" + " " * 2048 + "\n\n"
+
+ aiter = stream.__aiter__()
+ while True:
+ try:
+ chunk = await asyncio.wait_for(aiter.__anext__(), timeout=interval)
+ yield chunk
+ except asyncio.TimeoutError:
+ yield ": ping\n\n"
+ except StopAsyncIteration:
+ break
+ except asyncio.CancelledError:
+ break
# ---------------------------------------------------------------------------
@@ -261,15 +291,19 @@ async def chat_completions_endpoint(req: ChatCompletionRequest):
)
else:
+ request_overrides: dict | None = None
+ if req.deepsearch:
+ request_overrides = {"deepsearchPreset": req.deepsearch}
result = await chat_completions(
- model = req.model,
- messages = messages,
- stream = req.stream,
- thinking = req.thinking,
- tools = req.tools,
- tool_choice = req.tool_choice,
- temperature = req.temperature or 0.8,
- top_p = req.top_p or 0.95,
+ model = req.model,
+ messages = messages,
+ stream = req.stream,
+ thinking = req.thinking,
+ tools = req.tools,
+ tool_choice = req.tool_choice,
+ temperature = req.temperature or 0.8,
+ top_p = req.top_p or 0.95,
+ request_overrides = request_overrides,
)
except AppError:
@@ -281,6 +315,11 @@ async def chat_completions_endpoint(req: ChatCompletionRequest):
req.stream,
exc,
)
+ # Video failures must surface their real HTTP status code so downstream
+ # billing gateways (e.g. New API) don't misread an SSE-wrapped error as a
+ # successful 200 response.
+ if spec.is_video():
+ raise
if req.stream is not False:
_err_msg = str(exc) # capture before Python clears the except-scope variable
async def _err_stream():
@@ -292,7 +331,11 @@ async def chat_completions_endpoint(req: ChatCompletionRequest):
if isinstance(result, dict):
return JSONResponse(result)
- return StreamingResponse(_safe_sse(result), media_type="text/event-stream", headers=_SSE_HEADERS)
+ return StreamingResponse(
+ _sse_with_heartbeat(_safe_sse(result)),
+ media_type="text/event-stream",
+ headers=_SSE_HEADERS,
+ )
# ---------------------------------------------------------------------------
@@ -357,7 +400,7 @@ async def responses_endpoint(req: ResponsesCreateRequest):
if isinstance(result, dict):
return JSONResponse(result)
return StreamingResponse(
- _safe_sse_responses(result),
+ _sse_with_heartbeat(_safe_sse_responses(result)),
media_type = "text/event-stream",
headers = _SSE_HEADERS,
)
diff --git a/app/products/openai/schemas.py b/app/products/openai/schemas.py
index 9c5cfeb5..f2a6f954 100644
--- a/app/products/openai/schemas.py
+++ b/app/products/openai/schemas.py
@@ -40,6 +40,9 @@ class ChatCompletionRequest(BaseModel):
tool_choice: str | dict[str, Any] | None = None
parallel_tool_calls: bool | None = True
max_tokens: int | None = None
+ deepsearch: Literal["default", "deeper"] | None = Field(
+ None, description="深度搜索预设: default/deeper"
+ )
class ImageGenerationRequest(BaseModel):