mirror of
https://github.com/chenyme/grok2api.git
synced 2026-12-05 08:01:07 +00:00
feat: add configurable parallel blocked-recovery with distinct tokens
This commit is contained in:
1 parent
5bab7ae793
commit
5cc2f7913a
13 files changed
+429
-91
No files matched your search
@@ -4,7 +4,7 @@ from fastapi import APIRouter, Depends, HTTPException
|
||||
|
||||
from app.core.auth import verify_app_key
|
||||
from app.core.config import config
|
||||
from app.core.storage import get_storage, LocalStorage, RedisStorage, SQLStorage
|
||||
from app.core.storage import get_storage as resolve_storage, LocalStorage, RedisStorage, SQLStorage
|
||||
|
||||
router = APIRouter()
|
||||
|
||||
@@ -33,11 +33,11 @@ async def update_config(data: dict):
|
||||
|
||||
|
||||
@router.get("/storage", dependencies=[Depends(verify_app_key)])
|
||||
async def get_storage():
|
||||
async def get_storage_mode():
|
||||
"""获取当前存储模式"""
|
||||
storage_type = os.getenv("SERVER_STORAGE_TYPE", "").lower()
|
||||
if not storage_type:
|
||||
storage = get_storage()
|
||||
storage = resolve_storage()
|
||||
if isinstance(storage, LocalStorage):
|
||||
storage_type = "local"
|
||||
elif isinstance(storage, RedisStorage):
|
||||
|
||||
+106
-27
@@ -2,7 +2,7 @@
|
||||
Chat Completions API 路由
|
||||
"""
|
||||
|
||||
from typing import Any, Dict, List, Optional, Union
|
||||
from typing import Any, AsyncGenerator, AsyncIterable, Dict, List, Optional, Union
|
||||
import base64
|
||||
import binascii
|
||||
import time
|
||||
@@ -11,6 +11,7 @@ import uuid
|
||||
from fastapi import APIRouter
|
||||
from fastapi.responses import StreamingResponse, JSONResponse
|
||||
from pydantic import BaseModel, Field
|
||||
import orjson
|
||||
|
||||
from app.services.grok.services.chat import ChatService
|
||||
from app.services.grok.services.image import ImageGenerationService
|
||||
@@ -78,6 +79,7 @@ ALLOWED_IMAGE_SIZES = {
|
||||
"1024x1792",
|
||||
"1024x1024",
|
||||
}
|
||||
SUPERIMAGE_MODEL_ID = "grok-superimage-1.0"
|
||||
|
||||
|
||||
def _validate_media_input(value: str, field_name: str, param: str):
|
||||
@@ -165,6 +167,73 @@ def _image_field(response_format: str) -> str:
|
||||
return "url"
|
||||
return "b64_json"
|
||||
|
||||
|
||||
def _superimage_server_image_config() -> ImageConfig:
|
||||
"""Load server-side image generation parameters for grok-superimage-1.0."""
|
||||
n = int(get_config("superimage.n", 1) or 1)
|
||||
size = str(get_config("superimage.size", "1024x1024") or "1024x1024")
|
||||
response_format = str(
|
||||
get_config("superimage.response_format", get_config("app.image_format") or "url")
|
||||
or "url"
|
||||
)
|
||||
return ImageConfig(n=n, size=size, response_format=response_format)
|
||||
|
||||
|
||||
async def _safe_sse_stream(stream: AsyncIterable[str]) -> AsyncGenerator[str, None]:
|
||||
"""Ensure streaming endpoints return SSE error payloads instead of transport-level 5xx breaks."""
|
||||
try:
|
||||
async for chunk in stream:
|
||||
yield chunk
|
||||
except AppException as e:
|
||||
payload = {
|
||||
"error": {
|
||||
"message": e.message,
|
||||
"type": e.error_type,
|
||||
"code": e.code,
|
||||
}
|
||||
}
|
||||
yield f"event: error\ndata: {orjson.dumps(payload).decode()}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
except Exception as e:
|
||||
payload = {
|
||||
"error": {
|
||||
"message": str(e) or "stream_error",
|
||||
"type": "server_error",
|
||||
"code": "stream_error",
|
||||
}
|
||||
}
|
||||
yield f"event: error\ndata: {orjson.dumps(payload).decode()}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
|
||||
def _streaming_error_response(exc: Exception) -> StreamingResponse:
|
||||
if isinstance(exc, AppException):
|
||||
payload = {
|
||||
"error": {
|
||||
"message": exc.message,
|
||||
"type": exc.error_type,
|
||||
"code": exc.code,
|
||||
}
|
||||
}
|
||||
else:
|
||||
payload = {
|
||||
"error": {
|
||||
"message": str(exc) or "stream_error",
|
||||
"type": "server_error",
|
||||
"code": "stream_error",
|
||||
}
|
||||
}
|
||||
|
||||
async def _one_shot_error() -> AsyncGenerator[str, None]:
|
||||
yield f"event: error\ndata: {orjson.dumps(payload).decode()}\n\n"
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
return StreamingResponse(
|
||||
_one_shot_error(),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
||||
)
|
||||
|
||||
def _validate_image_config(image_conf: ImageConfig, *, stream: bool):
|
||||
n = image_conf.n or 1
|
||||
if n < 1 or n > 10:
|
||||
@@ -514,7 +583,7 @@ def validate_request(request: ChatCompletionRequest):
|
||||
param="messages",
|
||||
code="empty_prompt",
|
||||
)
|
||||
image_conf = request.image_config or ImageConfig()
|
||||
image_conf = _superimage_server_image_config() if request.model == SUPERIMAGE_MODEL_ID else (request.image_config or ImageConfig())
|
||||
n = image_conf.n or 1
|
||||
if not (1 <= n <= 10):
|
||||
raise ValidationException(
|
||||
@@ -669,7 +738,7 @@ async def chat_completions(request: ChatCompletionRequest):
|
||||
|
||||
if result.stream:
|
||||
return StreamingResponse(
|
||||
result.data,
|
||||
_safe_sse_stream(result.data),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
||||
)
|
||||
@@ -685,7 +754,7 @@ async def chat_completions(request: ChatCompletionRequest):
|
||||
is_stream = (
|
||||
request.stream if request.stream is not None else get_config("app.stream")
|
||||
)
|
||||
image_conf = request.image_config or ImageConfig()
|
||||
image_conf = _superimage_server_image_config() if request.model == SUPERIMAGE_MODEL_ID else (request.image_config or ImageConfig())
|
||||
_validate_image_config(image_conf, stream=bool(is_stream))
|
||||
response_format = _resolve_image_format(image_conf.response_format)
|
||||
response_field = _image_field(response_format)
|
||||
@@ -732,7 +801,7 @@ async def chat_completions(request: ChatCompletionRequest):
|
||||
|
||||
if result.stream:
|
||||
return StreamingResponse(
|
||||
result.data,
|
||||
_safe_sse_stream(result.data),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
||||
)
|
||||
@@ -747,34 +816,44 @@ async def chat_completions(request: ChatCompletionRequest):
|
||||
# 提取视频配置 (默认值在 Pydantic 模型中处理)
|
||||
v_conf = request.video_config or VideoConfig()
|
||||
|
||||
result = await VideoService.completions(
|
||||
model=request.model,
|
||||
messages=[msg.model_dump() for msg in request.messages],
|
||||
stream=request.stream,
|
||||
reasoning_effort=request.reasoning_effort,
|
||||
aspect_ratio=v_conf.aspect_ratio,
|
||||
video_length=v_conf.video_length,
|
||||
resolution=v_conf.resolution_name,
|
||||
preset=v_conf.preset,
|
||||
)
|
||||
try:
|
||||
result = await VideoService.completions(
|
||||
model=request.model,
|
||||
messages=[msg.model_dump() for msg in request.messages],
|
||||
stream=request.stream,
|
||||
reasoning_effort=request.reasoning_effort,
|
||||
aspect_ratio=v_conf.aspect_ratio,
|
||||
video_length=v_conf.video_length,
|
||||
resolution=v_conf.resolution_name,
|
||||
preset=v_conf.preset,
|
||||
)
|
||||
except Exception as e:
|
||||
if request.stream is not False:
|
||||
return _streaming_error_response(e)
|
||||
raise
|
||||
else:
|
||||
result = await ChatService.completions(
|
||||
model=request.model,
|
||||
messages=[msg.model_dump() for msg in request.messages],
|
||||
stream=request.stream,
|
||||
reasoning_effort=request.reasoning_effort,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
tools=request.tools,
|
||||
tool_choice=request.tool_choice,
|
||||
parallel_tool_calls=request.parallel_tool_calls,
|
||||
)
|
||||
try:
|
||||
result = await ChatService.completions(
|
||||
model=request.model,
|
||||
messages=[msg.model_dump() for msg in request.messages],
|
||||
stream=request.stream,
|
||||
reasoning_effort=request.reasoning_effort,
|
||||
temperature=request.temperature,
|
||||
top_p=request.top_p,
|
||||
tools=request.tools,
|
||||
tool_choice=request.tool_choice,
|
||||
parallel_tool_calls=request.parallel_tool_calls,
|
||||
)
|
||||
except Exception as e:
|
||||
if request.stream is not False:
|
||||
return _streaming_error_response(e)
|
||||
raise
|
||||
|
||||
if isinstance(result, dict):
|
||||
return JSONResponse(content=result)
|
||||
else:
|
||||
return StreamingResponse(
|
||||
result,
|
||||
_safe_sse_stream(result),
|
||||
media_type="text/event-stream",
|
||||
headers={"Cache-Control": "no-cache", "Connection": "keep-alive"},
|
||||
)
|
||||
|
||||
+13
-2
@@ -250,18 +250,29 @@ class Config:
|
||||
|
||||
# 自动回填缺失配置到存储
|
||||
# 或迁移了配置后需要更新
|
||||
# 保护:当远程存储返回 None 且本地也没有可迁移配置时,不覆盖远程配置,避免误重置。
|
||||
has_local_seed = bool(config_data)
|
||||
allow_bootstrap_empty_remote = (
|
||||
(not from_remote) and has_local_seed
|
||||
)
|
||||
should_persist = (
|
||||
(not from_remote) or (merged != config_data) or deprecated_sections
|
||||
allow_bootstrap_empty_remote
|
||||
or (merged != config_data and bool(config_data))
|
||||
or deprecated_sections
|
||||
)
|
||||
if should_persist:
|
||||
async with storage.acquire_lock("config_save", timeout=10):
|
||||
await storage.save_config(merged)
|
||||
if not from_remote:
|
||||
if not from_remote and has_local_seed:
|
||||
logger.info(
|
||||
f"Initialized remote storage ({storage.__class__.__name__}) with config baseline."
|
||||
)
|
||||
if deprecated_sections:
|
||||
logger.info("Configuration automatically migrated and cleaned.")
|
||||
elif not from_remote and not has_local_seed:
|
||||
logger.warning(
|
||||
"Skip persisting defaults: empty config source detected, keep runtime merged config only."
|
||||
)
|
||||
|
||||
self._config = merged
|
||||
except Exception as e:
|
||||
|
||||
@@ -22,7 +22,7 @@ from app.core.exceptions import (
|
||||
from app.services.grok.services.model import ModelService
|
||||
from app.services.grok.utils.upload import UploadService
|
||||
from app.services.grok.utils import process as proc_base
|
||||
from app.services.grok.utils.retry import pick_token, rate_limited
|
||||
from app.services.grok.utils.retry import pick_token, rate_limited, transient_upstream
|
||||
from app.services.reverse.app_chat import AppChatReverse
|
||||
from app.services.reverse.utils.session import ResettableSession
|
||||
from app.services.grok.utils.stream import wrap_stream_with_usage
|
||||
@@ -411,7 +411,7 @@ class ChatService:
|
||||
|
||||
# 跨 Token 重试循环
|
||||
tried_tokens = set()
|
||||
max_token_retries = int(get_config("retry.max_retry"))
|
||||
max_token_retries = int(get_config("retry.max_retry") or 3)
|
||||
last_error = None
|
||||
|
||||
for attempt in range(max_token_retries):
|
||||
@@ -481,6 +481,20 @@ class ChatService:
|
||||
)
|
||||
continue
|
||||
|
||||
if transient_upstream(e):
|
||||
has_alternative_token = False
|
||||
for pool_name in ModelService.pool_candidates_for_model(model):
|
||||
if token_mgr.get_token(pool_name, exclude=tried_tokens):
|
||||
has_alternative_token = True
|
||||
break
|
||||
if not has_alternative_token:
|
||||
raise
|
||||
logger.warning(
|
||||
f"Transient upstream error for token {token[:10]}..., "
|
||||
f"trying next token (attempt {attempt + 1}/{max_token_retries}): {e}"
|
||||
)
|
||||
continue
|
||||
|
||||
# 非 429 错误,不换 token,直接抛出
|
||||
raise
|
||||
|
||||
|
||||
@@ -52,7 +52,7 @@ class ImageGenerationService:
|
||||
enable_nsfw: Optional[bool] = None,
|
||||
chat_format: bool = False,
|
||||
) -> ImageGenerationResult:
|
||||
max_token_retries = int(get_config("retry.max_retry"))
|
||||
max_token_retries = int(get_config("retry.max_retry") or 3)
|
||||
tried_tokens: set[str] = set()
|
||||
last_error: Optional[Exception] = None
|
||||
|
||||
@@ -138,6 +138,7 @@ class ImageGenerationService:
|
||||
token_mgr=token_mgr,
|
||||
token=current_token,
|
||||
model_info=model_info,
|
||||
tried_tokens=tried_tokens,
|
||||
prompt=prompt,
|
||||
n=n,
|
||||
response_format=response_format,
|
||||
@@ -180,12 +181,15 @@ class ImageGenerationService:
|
||||
) -> ImageGenerationResult:
|
||||
if enable_nsfw is None:
|
||||
enable_nsfw = bool(get_config("image.nsfw"))
|
||||
stream_retries = int(get_config("image.blocked_parallel_attempts") or 5) + 1
|
||||
stream_retries = max(1, min(stream_retries, 10))
|
||||
upstream = image_service.stream(
|
||||
token=token,
|
||||
prompt=prompt,
|
||||
aspect_ratio=aspect_ratio,
|
||||
n=n,
|
||||
enable_nsfw=enable_nsfw,
|
||||
max_retries=stream_retries,
|
||||
)
|
||||
processor = ImageWSStreamProcessor(
|
||||
model_info.model_id,
|
||||
@@ -209,6 +213,7 @@ class ImageGenerationService:
|
||||
token_mgr: Any,
|
||||
token: str,
|
||||
model_info: Any,
|
||||
tried_tokens: set[str],
|
||||
prompt: str,
|
||||
n: int,
|
||||
response_format: str,
|
||||
@@ -223,9 +228,9 @@ class ImageGenerationService:
|
||||
calls_needed = max(1, int(math.ceil(n / expected_per_call)))
|
||||
calls_needed = min(calls_needed, n)
|
||||
|
||||
async def _fetch_batch(call_target: int):
|
||||
async def _fetch_batch(call_target: int, call_token: str):
|
||||
upstream = image_service.stream(
|
||||
token=token,
|
||||
token=call_token,
|
||||
prompt=prompt,
|
||||
aspect_ratio=aspect_ratio,
|
||||
n=call_target,
|
||||
@@ -243,7 +248,7 @@ class ImageGenerationService:
|
||||
for i in range(calls_needed):
|
||||
remaining = n - (i * expected_per_call)
|
||||
call_target = min(expected_per_call, remaining)
|
||||
tasks.append(_fetch_batch(call_target))
|
||||
tasks.append(_fetch_batch(call_target, token))
|
||||
|
||||
results = await asyncio.gather(*tasks, return_exceptions=True)
|
||||
for batch in results:
|
||||
@@ -259,6 +264,84 @@ class ImageGenerationService:
|
||||
if len(all_images) >= n:
|
||||
break
|
||||
|
||||
# If upstream likely blocked/reviewed some images, run extra parallel attempts
|
||||
# and only keep valid finals selected by ws_imagine classification.
|
||||
if len(all_images) < n:
|
||||
remaining = n - len(all_images)
|
||||
extra_attempts = int(get_config("image.blocked_parallel_attempts") or 5)
|
||||
extra_attempts = max(0, min(extra_attempts, 10))
|
||||
parallel_enabled = bool(get_config("image.blocked_parallel_enabled", True))
|
||||
if extra_attempts > 0:
|
||||
logger.warning(
|
||||
f"Image finals insufficient ({len(all_images)}/{n}), running "
|
||||
f"{extra_attempts} recovery attempts for remaining={remaining}, "
|
||||
f"parallel_enabled={parallel_enabled}"
|
||||
)
|
||||
extra_tasks = []
|
||||
if parallel_enabled:
|
||||
recovery_tried = set(tried_tokens)
|
||||
recovery_tokens: List[str] = []
|
||||
for _ in range(extra_attempts):
|
||||
recovery_token = await pick_token(
|
||||
token_mgr,
|
||||
model_info.model_id,
|
||||
recovery_tried,
|
||||
)
|
||||
if not recovery_token:
|
||||
break
|
||||
recovery_tried.add(recovery_token)
|
||||
recovery_tokens.append(recovery_token)
|
||||
|
||||
if recovery_tokens:
|
||||
logger.info(
|
||||
f"Recovery using {len(recovery_tokens)} distinct tokens"
|
||||
)
|
||||
for recovery_token in recovery_tokens:
|
||||
extra_tasks.append(
|
||||
_fetch_batch(min(expected_per_call, remaining), recovery_token)
|
||||
)
|
||||
else:
|
||||
extra_tasks = [
|
||||
_fetch_batch(min(expected_per_call, remaining), token)
|
||||
for _ in range(extra_attempts)
|
||||
]
|
||||
|
||||
if not extra_tasks:
|
||||
logger.warning("No tokens available for recovery attempts")
|
||||
extra_results = []
|
||||
else:
|
||||
extra_results = await asyncio.gather(*extra_tasks, return_exceptions=True)
|
||||
for batch in extra_results:
|
||||
if isinstance(batch, Exception):
|
||||
logger.warning(f"WS recovery batch failed: {batch}")
|
||||
continue
|
||||
for img in batch:
|
||||
if img not in seen:
|
||||
seen.add(img)
|
||||
all_images.append(img)
|
||||
if len(all_images) >= n:
|
||||
break
|
||||
if len(all_images) >= n:
|
||||
break
|
||||
logger.info(
|
||||
f"Image recovery attempts completed: finals={len(all_images)}/{n}, "
|
||||
f"attempts={extra_attempts}"
|
||||
)
|
||||
|
||||
if len(all_images) < n:
|
||||
logger.error(
|
||||
f"Image generation failed after recovery attempts: finals={len(all_images)}/{n}, "
|
||||
f"blocked_parallel_attempts={int(get_config('image.blocked_parallel_attempts') or 5)}"
|
||||
)
|
||||
raise UpstreamException(
|
||||
"Image generation blocked or no valid final image",
|
||||
details={
|
||||
"error_code": "blocked_no_final_image",
|
||||
"final_images": len(all_images),
|
||||
"requested": n,
|
||||
},
|
||||
)
|
||||
|
||||
try:
|
||||
await token_mgr.consume(token, self._get_effort(model_info))
|
||||
except Exception as e:
|
||||
@@ -436,6 +519,7 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
|
||||
async def process(self, response: AsyncIterable[dict]) -> AsyncGenerator[str, None]:
|
||||
images: Dict[str, Dict] = {}
|
||||
emitted_chat_chunk = False
|
||||
|
||||
async for item in response:
|
||||
if item.get("type") == "error":
|
||||
@@ -475,6 +559,9 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
continue
|
||||
|
||||
if item.get("stage") != "final":
|
||||
# Chat Completions image stream should only expose final results.
|
||||
if self.chat_format:
|
||||
continue
|
||||
if image_id not in self._initial_sent:
|
||||
self._initial_sent.add(image_id)
|
||||
stage = item.get("stage") or "preview"
|
||||
@@ -515,6 +602,7 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
if not self._id_generated:
|
||||
self._response_id = make_response_id()
|
||||
self._id_generated = True
|
||||
emitted_chat_chunk = True
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
@@ -541,33 +629,36 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
)
|
||||
|
||||
if self.n == 1:
|
||||
if self._target_id and self._target_id in images:
|
||||
if (
|
||||
self._target_id
|
||||
and self._target_id in images
|
||||
and images[self._target_id].get("is_final", False)
|
||||
):
|
||||
selected = [(self._target_id, images[self._target_id])]
|
||||
else:
|
||||
final_candidates = [
|
||||
item for item in images.items() if item[1].get("is_final", False)
|
||||
]
|
||||
selected = (
|
||||
[
|
||||
max(
|
||||
images.items(),
|
||||
key=lambda x: (
|
||||
x[1].get("is_final", False),
|
||||
x[1].get("blob_size", 0),
|
||||
),
|
||||
)
|
||||
]
|
||||
if images
|
||||
[max(final_candidates, key=lambda x: x[1].get("blob_size", 0))]
|
||||
if final_candidates
|
||||
else []
|
||||
)
|
||||
else:
|
||||
selected = [
|
||||
(image_id, images[image_id])
|
||||
for image_id in self._index_map
|
||||
if image_id in images
|
||||
if image_id in images and images[image_id].get("is_final", False)
|
||||
]
|
||||
|
||||
for image_id, item in selected:
|
||||
if self.response_format == "url":
|
||||
final_image_id = image_id
|
||||
# Keep original imagine image name for superimage chat stream output.
|
||||
if self.model != "grok-superimage-1.0":
|
||||
final_image_id = f"{image_id}-final"
|
||||
output = await self._save_blob(
|
||||
f"{image_id}-final",
|
||||
final_image_id,
|
||||
item.get("blob", ""),
|
||||
item.get("is_final", False),
|
||||
ext=item.get("ext"),
|
||||
@@ -593,6 +684,7 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
|
||||
if self.chat_format:
|
||||
# OpenAI ChatCompletion chunk format
|
||||
emitted_chat_chunk = True
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
@@ -624,6 +716,23 @@ class ImageWSStreamProcessor(ImageWSBaseProcessor):
|
||||
},
|
||||
)
|
||||
|
||||
if self.chat_format:
|
||||
if not self._id_generated:
|
||||
self._response_id = make_response_id()
|
||||
self._id_generated = True
|
||||
if not emitted_chat_chunk:
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
self._response_id,
|
||||
self.model,
|
||||
"",
|
||||
index=0,
|
||||
is_final=True,
|
||||
),
|
||||
)
|
||||
yield "data: [DONE]\n\n"
|
||||
|
||||
|
||||
class ImageWSCollectProcessor(ImageWSBaseProcessor):
|
||||
"""WebSocket image non-stream processor."""
|
||||
@@ -649,8 +758,8 @@ class ImageWSCollectProcessor(ImageWSBaseProcessor):
|
||||
images[image_id] = self._pick_best(images.get(image_id), item)
|
||||
|
||||
selected = sorted(
|
||||
images.values(),
|
||||
key=lambda x: (x.get("is_final", False), x.get("blob_size", 0)),
|
||||
[item for item in images.values() if item.get("is_final", False)],
|
||||
key=lambda x: x.get("blob_size", 0),
|
||||
reverse=True,
|
||||
)
|
||||
if self.n:
|
||||
|
||||
@@ -66,7 +66,7 @@ class ImageEditService:
|
||||
)
|
||||
images = images[-3:]
|
||||
|
||||
max_token_retries = int(get_config("retry.max_retry"))
|
||||
max_token_retries = int(get_config("retry.max_retry") or 3)
|
||||
tried_tokens: set[str] = set()
|
||||
last_error: Exception | None = None
|
||||
|
||||
@@ -323,6 +323,7 @@ class ImageStreamProcessor(BaseProcessor):
|
||||
) -> AsyncGenerator[str, None]:
|
||||
"""Process stream response."""
|
||||
final_images = []
|
||||
emitted_chat_chunk = False
|
||||
idle_timeout = get_config("image.stream_timeout")
|
||||
|
||||
try:
|
||||
@@ -347,21 +348,7 @@ class ImageStreamProcessor(BaseProcessor):
|
||||
|
||||
out_index = 0 if self.n == 1 else image_index
|
||||
|
||||
if self.chat_format:
|
||||
# OpenAI ChatCompletion chunk format for partial
|
||||
if not self._id_generated:
|
||||
self._response_id = make_response_id()
|
||||
self._id_generated = True
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
self._response_id,
|
||||
self.model,
|
||||
"",
|
||||
index=out_index,
|
||||
),
|
||||
)
|
||||
else:
|
||||
if not self.chat_format:
|
||||
yield self._sse(
|
||||
"image_generation.partial_image",
|
||||
{
|
||||
@@ -421,6 +408,7 @@ class ImageStreamProcessor(BaseProcessor):
|
||||
|
||||
if self.chat_format:
|
||||
# OpenAI ChatCompletion chunk format
|
||||
emitted_chat_chunk = True
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
@@ -450,6 +438,23 @@ class ImageStreamProcessor(BaseProcessor):
|
||||
},
|
||||
},
|
||||
)
|
||||
|
||||
if self.chat_format:
|
||||
if not self._id_generated:
|
||||
self._response_id = make_response_id()
|
||||
self._id_generated = True
|
||||
if not emitted_chat_chunk:
|
||||
yield self._sse(
|
||||
"chat.completion.chunk",
|
||||
make_chat_chunk(
|
||||
self._response_id,
|
||||
self.model,
|
||||
"",
|
||||
index=0,
|
||||
is_final=True,
|
||||
),
|
||||
)
|
||||
yield "data: [DONE]\n\n"
|
||||
except asyncio.CancelledError:
|
||||
logger.debug("Image stream cancelled by client")
|
||||
except StreamIdleTimeoutError as e:
|
||||
|
||||
@@ -174,6 +174,18 @@ class ModelService:
|
||||
is_image_edit=False,
|
||||
is_video=False,
|
||||
),
|
||||
ModelInfo(
|
||||
model_id="grok-superimage-1.0",
|
||||
grok_model="grok-3",
|
||||
model_mode="MODEL_MODE_FAST",
|
||||
tier=Tier.BASIC,
|
||||
cost=Cost.HIGH,
|
||||
display_name="Grok SuperImage",
|
||||
description="Imagine waterfall image generation model for chat completions",
|
||||
is_image=True,
|
||||
is_image_edit=False,
|
||||
is_video=False,
|
||||
),
|
||||
ModelInfo(
|
||||
model_id="grok-imagine-1.0",
|
||||
grok_model="grok-3",
|
||||
|
||||
@@ -42,4 +42,24 @@ def rate_limited(error: Exception) -> bool:
|
||||
return status == 429 or code == "rate_limit_exceeded"
|
||||
|
||||
|
||||
__all__ = ["pick_token", "rate_limited"]
|
||||
def transient_upstream(error: Exception) -> bool:
|
||||
"""Whether error is likely transient and safe to retry with another token."""
|
||||
if not isinstance(error, UpstreamException):
|
||||
return False
|
||||
details = error.details or {}
|
||||
status = details.get("status")
|
||||
err = str(details.get("error") or error).lower()
|
||||
transient_status = {408, 500, 502, 503, 504}
|
||||
if status in transient_status:
|
||||
return True
|
||||
timeout_markers = (
|
||||
"timed out",
|
||||
"timeout",
|
||||
"connection reset",
|
||||
"temporarily unavailable",
|
||||
"http2",
|
||||
)
|
||||
return any(marker in err for marker in timeout_markers)
|
||||
|
||||
|
||||
__all__ = ["pick_token", "rate_limited", "transient_upstream"]
|
||||
@@ -4,6 +4,7 @@ Reverse interface: app chat conversations.
|
||||
|
||||
import orjson
|
||||
from typing import Any, Dict, List, Optional
|
||||
from urllib.parse import urlparse
|
||||
from curl_cffi.requests import AsyncSession
|
||||
|
||||
from app.core.logger import logger
|
||||
@@ -16,6 +17,19 @@ from app.services.reverse.utils.retry import retry_on_status
|
||||
CHAT_API = "https://grok.com/rest/app-chat/conversations/new"
|
||||
|
||||
|
||||
def _normalize_chat_proxy(proxy_url: str) -> str:
|
||||
"""Normalize proxy URL for curl-cffi app-chat requests."""
|
||||
if not proxy_url:
|
||||
return proxy_url
|
||||
parsed = urlparse(proxy_url)
|
||||
scheme = parsed.scheme.lower()
|
||||
if scheme == "socks5":
|
||||
return proxy_url.replace("socks5://", "socks5h://", 1)
|
||||
if scheme == "socks4":
|
||||
return proxy_url.replace("socks4://", "socks4a://", 1)
|
||||
return proxy_url
|
||||
|
||||
|
||||
class AppChatReverse:
|
||||
"""/rest/app-chat/conversations/new reverse interface."""
|
||||
|
||||
@@ -102,7 +116,21 @@ class AppChatReverse:
|
||||
try:
|
||||
# Get proxies
|
||||
base_proxy = get_config("proxy.base_proxy_url")
|
||||
proxies = {"http": base_proxy, "https": base_proxy} if base_proxy else None
|
||||
proxy = None
|
||||
proxies = None
|
||||
if base_proxy:
|
||||
normalized_proxy = _normalize_chat_proxy(base_proxy)
|
||||
scheme = urlparse(normalized_proxy).scheme.lower()
|
||||
if scheme.startswith("socks"):
|
||||
# curl_cffi 对 SOCKS 代理优先使用 proxy 参数,避免被按 HTTP CONNECT 处理
|
||||
proxy = normalized_proxy
|
||||
else:
|
||||
proxies = {"http": normalized_proxy, "https": normalized_proxy}
|
||||
logger.info(
|
||||
f"AppChatReverse proxy enabled: scheme={scheme}, target={normalized_proxy}"
|
||||
)
|
||||
else:
|
||||
logger.warning("AppChatReverse proxy is empty, request will use direct network")
|
||||
|
||||
# Build headers
|
||||
headers = build_headers(
|
||||
@@ -123,11 +151,12 @@ class AppChatReverse:
|
||||
)
|
||||
|
||||
# Curl Config
|
||||
timeout = max(
|
||||
float(get_config("chat.timeout") or 0),
|
||||
float(get_config("video.timeout") or 0),
|
||||
float(get_config("image.timeout") or 0),
|
||||
)
|
||||
timeout = float(get_config("chat.timeout") or 0)
|
||||
if timeout <= 0:
|
||||
timeout = max(
|
||||
float(get_config("video.timeout") or 0),
|
||||
float(get_config("image.timeout") or 0),
|
||||
)
|
||||
browser = get_config("proxy.browser")
|
||||
|
||||
async def _do_request():
|
||||
@@ -137,6 +166,7 @@ class AppChatReverse:
|
||||
data=orjson.dumps(payload),
|
||||
timeout=timeout,
|
||||
stream=True,
|
||||
proxy=proxy,
|
||||
proxies=proxies,
|
||||
impersonate=browser,
|
||||
)
|
||||
|
||||
@@ -37,10 +37,9 @@ class ImagineWebSocketReverse:
|
||||
return match.group(1), match.group(2).lower()
|
||||
|
||||
def _is_final_image(self, url: str, blob_size: int, final_min_bytes: int) -> bool:
|
||||
url_lower = (url or "").lower()
|
||||
if url_lower.endswith((".jpg", ".jpeg")):
|
||||
return True
|
||||
return blob_size > final_min_bytes
|
||||
# Final image must satisfy byte-size threshold to avoid tiny preview
|
||||
# images being treated as final outputs.
|
||||
return blob_size >= final_min_bytes
|
||||
|
||||
def _classify_image(self, url: str, blob: str, final_min_bytes: int, medium_min_bytes: int) -> Optional[Dict[str, object]]:
|
||||
if not url or not blob:
|
||||
@@ -116,15 +115,18 @@ class ImagineWebSocketReverse:
|
||||
yield item
|
||||
return
|
||||
except _BlockedError:
|
||||
if yielded_any or attempt + 1 >= retries:
|
||||
if not yielded_any:
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": "blocked",
|
||||
"error": "blocked_no_final_image",
|
||||
}
|
||||
return
|
||||
logger.warning(f"WebSocket blocked, retry {attempt + 1}/{retries}")
|
||||
if attempt + 1 < retries:
|
||||
logger.warning(
|
||||
f"WebSocket blocked/reviewed, retry {attempt + 1}/{retries}"
|
||||
)
|
||||
continue
|
||||
yield {
|
||||
"type": "error",
|
||||
"error_code": "blocked",
|
||||
"error": "blocked_no_final_image",
|
||||
"yielded_partial": yielded_any,
|
||||
}
|
||||
return
|
||||
except Exception as e:
|
||||
logger.error(f"WebSocket stream failed: {e}")
|
||||
yield {
|
||||
@@ -198,6 +200,10 @@ class ImagineWebSocketReverse:
|
||||
and completed == 0
|
||||
and now - medium_received_time > blocked_grace
|
||||
):
|
||||
logger.warning(
|
||||
"Imagine stream blocked suspected: received medium preview but no valid final image "
|
||||
f"within {blocked_grace:.1f}s (request_id={request_id})"
|
||||
)
|
||||
raise _BlockedError()
|
||||
if completed > 0 and now - last_activity > 10:
|
||||
logger.info(
|
||||
@@ -259,6 +265,11 @@ class ImagineWebSocketReverse:
|
||||
and completed == 0
|
||||
and time.monotonic() - medium_received_time > final_timeout
|
||||
):
|
||||
logger.warning(
|
||||
"Imagine stream final-timeout suspected review/block: "
|
||||
f"no final image reached threshold in {final_timeout:.1f}s "
|
||||
f"(request_id={request_id})"
|
||||
)
|
||||
raise _BlockedError()
|
||||
|
||||
elif ws_msg.type in (
|
||||
|
||||
@@ -29,6 +29,7 @@ const NUMERIC_FIELDS = new Set([
|
||||
'final_timeout',
|
||||
'final_min_bytes',
|
||||
'medium_min_bytes',
|
||||
'blocked_parallel_attempts',
|
||||
'concurrent',
|
||||
'batch_size'
|
||||
]);
|
||||
@@ -96,7 +97,17 @@ const LOCALE_MAP = {
|
||||
"final_timeout": { title: "最终图超时", desc: "收到中等图后等待最终图的超时秒数。" },
|
||||
"nsfw": { title: "NSFW 模式", desc: "WebSocket 请求是否启用 NSFW。" },
|
||||
"medium_min_bytes": { title: "中等图最小字节", desc: "判定中等质量图的最小字节数。" },
|
||||
"final_min_bytes": { title: "最终图最小字节", desc: "判定最终图的最小字节数(通常 JPG > 100KB)。" }
|
||||
"final_min_bytes": { title: "最终图最小字节", desc: "判定最终图的最小字节数(通常 JPG > 100KB)。" },
|
||||
"blocked_parallel_enabled": { title: "启用并行补偿", desc: "疑似审查/拦截时,是否启用并行补偿生成。" },
|
||||
"blocked_parallel_attempts": { title: "拦截补偿并发次数", desc: "疑似审查/拦截导致无最终图时,自动并行补偿生成次数。" }
|
||||
},
|
||||
|
||||
|
||||
"superimage": {
|
||||
"label": "SuperImage 配置",
|
||||
"n": { title: "生成数量", desc: "仅用于 grok-superimage-1.0 的服务端统一生成数量(1-10)。" },
|
||||
"size": { title: "图片尺寸", desc: "仅用于 grok-superimage-1.0 的服务端统一尺寸。" },
|
||||
"response_format": { title: "响应格式", desc: "仅用于 grok-superimage-1.0 的服务端统一返回格式。" }
|
||||
},
|
||||
|
||||
|
||||
@@ -412,6 +423,22 @@ function buildFieldCard(section, key, val) {
|
||||
{ val: 'url', text: 'URL' }
|
||||
]);
|
||||
}
|
||||
else if (section === 'superimage' && key === 'size') {
|
||||
built = buildSelectInput(section, key, val, [
|
||||
{ val: '1024x1024', text: '1024x1024 (1:1)' },
|
||||
{ val: '1280x720', text: '1280x720 (16:9)' },
|
||||
{ val: '720x1280', text: '720x1280 (9:16)' },
|
||||
{ val: '1792x1024', text: '1792x1024 (3:2)' },
|
||||
{ val: '1024x1792', text: '1024x1792 (2:3)' }
|
||||
]);
|
||||
}
|
||||
else if (section === 'superimage' && key === 'response_format') {
|
||||
built = buildSelectInput(section, key, val, [
|
||||
{ val: 'url', text: 'URL' },
|
||||
{ val: 'b64_json', text: 'B64 JSON' },
|
||||
{ val: 'base64', text: 'Base64' }
|
||||
]);
|
||||
}
|
||||
else if (Array.isArray(val) || typeof val === 'object') {
|
||||
built = buildJsonInput(section, key, val);
|
||||
}
|
||||
|
||||
@@ -109,6 +109,21 @@ nsfw = true
|
||||
medium_min_bytes = 30000
|
||||
# 判定为最终图的最小字节数
|
||||
final_min_bytes = 100000
|
||||
# 遇到疑似审查/拦截时的并行补偿生成次数
|
||||
blocked_parallel_attempts = 5
|
||||
# 是否启用并行补偿(启用时优先使用不同 token)
|
||||
blocked_parallel_enabled = true
|
||||
|
||||
|
||||
# ==================== SuperImage 配置 ====================
|
||||
[superimage]
|
||||
# 仅对 grok-superimage-1.0 生效,由服务端统一控制,不使用客户端 image_config
|
||||
n = 1
|
||||
# 图片尺寸:1280x720 / 720x1280 / 1792x1024 / 1024x1792 / 1024x1024
|
||||
size = "1024x1024"
|
||||
# 响应格式:url / b64_json / base64
|
||||
response_format = "url"
|
||||
|
||||
|
||||
# ==================== 视频配置 ====================
|
||||
[video]
|
||||
|
||||
@@ -109,6 +109,7 @@ docker compose up -d
|
||||
| `grok-4.1-thinking` | 4 | Basic/Super | 支持 | 支持 | - |
|
||||
| `grok-4.20-beta` | 1 | Basic/Super | 支持 | 支持 | - |
|
||||
| `grok-imagine-1.0` | - | Basic/Super | - | 支持 | - |
|
||||
| `grok-superimage-1.0` | - | Basic/Super | - | 支持 | - |
|
||||
| `grok-imagine-1.0-edit` | - | Basic/Super | - | 支持 | - |
|
||||
| `grok-imagine-1.0-video` | - | Basic/Super | - | - | 支持 |
|
||||
|
||||
@@ -151,7 +152,7 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
| └─`video_length` | integer | 视频时长 (秒) | `6`, `10`, `15` |
|
||||
| └─`resolution_name` | string | 分辨率 | `480p`, `720p` |
|
||||
| └─`preset` | string | 风格预设 | `fun`, `normal`, `spicy`, `custom` |
|
||||
| `image_config` | object | **图片模型专用配置对象** | 支持:`grok-imagine-1.0` / `grok-imagine-1.0-edit` |
|
||||
| `image_config` | object | **图片模型专用配置对象** | 支持:`grok-imagine-1.0` / `grok-superimage-1.0` / `grok-imagine-1.0-edit` |
|
||||
| └─`n` | integer | 生成数量 | `1` ~ `10` |
|
||||
| └─`size` | string | 图片尺寸 | `1280x720`, `720x1280`, `1792x1024`, `1024x1792`, `1024x1024` |
|
||||
| └─`response_format` | string | 响应格式 | `url`, `b64_json`, `base64` |
|
||||
@@ -177,6 +178,10 @@ curl http://localhost:8000/v1/chat/completions \
|
||||
- `image_url/input_audio/file` 仅支持 URL 或 Data URI(`data:<mime>;base64,...`),裸 base64 会报错。
|
||||
- `reasoning_effort`:`none` 表示不输出思考,其他值都会输出思考内容。
|
||||
- 工具调用为**提示词模拟 + 客户端执行回填**:模型通过 `<tool_call>{...}</tool_call>` 输出调用请求,服务端解析为 `tool_calls`;不执行工具。
|
||||
- `grok-superimage-1.0` 与瀑布流 imagine 生成链路一致,可直接通过 `/v1/chat/completions` 调用;其 `n/size/response_format` 由服务端 `[superimage]` 统一控制。
|
||||
- `grok-superimage-1.0` 在 `/v1/chat/completions` 的流式输出仅返回最终成图,不返回中间预览图。
|
||||
- `grok-superimage-1.0` 流式 URL 出图会保持原始图片名(不追加 `-final` 后缀)。
|
||||
- 当图片疑似被审查拦截导致无最终图时,若开启 `image.blocked_parallel_enabled`,服务端会按 `image.blocked_parallel_attempts` 自动并行补偿生成,并优先使用不同 token;若仍无满足 `image.final_min_bytes` 的最终图则返回失败。
|
||||
- `grok-imagine-1.0-edit` 必须提供图片,多图默认取**最后 3 张**与最后一个文本。
|
||||
- `grok-imagine-1.0-video` 支持文生视频与图生视频(通过 `image_url` 传参考图,**仅取第 1 张**)。
|
||||
- 除上述外的其他参数将自动丢弃并忽略。
|
||||
|
||||
Reference in new issue
Block a user