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):