mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-06 00:01:05 +00:00
feat: port 本地自定义补丁到新架构
上游大重构后以下本地补丁重新迁移到 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 清理消息中 <think>...</think> 块和
内联 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 等计费网关误判为成功扣费。
This commit is contained in:
1 parent
118fe454c2
commit
44a50d3d4d
3 files changed
+75
-14
No files matched your search
@@ -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"<think>[\s\S]*?</think>")
|
||||
_INLINE_BASE64_IMG_RE = re.compile(r"!\[image\]\(data:[^)]*?base64,[^)]*?\)")
|
||||
|
||||
|
||||
def _strip_think_and_inline_images(text: str) -> str:
|
||||
"""Remove <think>...</think> 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":
|
||||
|
||||
@@ -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,
|
||||
)
|
||||
|
||||
@@ -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):
|
||||
|
||||
Reference in new issue
Block a user