[Feature] add a new response_format is file type when image generate (#1673)

Signed-off-by: rongfu.leng <lenronfu@gmail.com>
Co-authored-by: Gao Han <hgaoaf@connect.ust.hk>
This commit is contained in:
rongfu.lengandGao Han authored and GitHub committed 2026-06-24 09:04:13 +08:00
1 parent 6dc4638a7e
commit a2d1dafc65
4 files changed
+150 -5

No files matched your search

+9 -2
View File
@@ -110,6 +110,7 @@ from vllm_omni.entrypoints.openai.protocol.images import (
ImageData,
ImageGenerationRequest,
ImageGenerationResponse,
ResponseFormat,
)
from vllm_omni.entrypoints.openai.protocol.videos import (
SecondStr,
@@ -1706,6 +1707,7 @@ async def show_available_models(raw_request: Request) -> JSONResponse:
@router.post(
"/v1/images/generations",
dependencies=[Depends(validate_json_request)],
response_model=None,
responses={
HTTPStatus.OK.value: {"model": ImageGenerationResponse},
HTTPStatus.BAD_REQUEST.value: {"model": ErrorResponse},
@@ -1714,7 +1716,9 @@ async def show_available_models(raw_request: Request) -> JSONResponse:
},
)
@with_cancellation
async def generate_images(request: ImageGenerationRequest, raw_request: Request):
async def generate_images(
request: ImageGenerationRequest, raw_request: Request
) -> ImageGenerationResponse | StreamingResponse:
"""Generate images from text prompts using diffusion models.
OpenAI DALL-E compatible endpoint for text-to-image generation.
@@ -1906,7 +1910,10 @@ async def generate_images(request: ImageGenerationRequest, raw_request: Request)
}
if request.size:
response_kwargs["size"] = size_str
return ImageGenerationResponse(**response_kwargs)
response = ImageGenerationResponse(**response_kwargs)
if request.response_format != ResponseFormat.FILE:
return response
return response.stream_response()
except (EngineGenerateError, EngineDeadError) as exc:
return _create_engine_error_json_response(raw_request, exc)
@@ -7,9 +7,16 @@ This module provides Pydantic models that follow the OpenAI DALL-E API specifica
for text-to-image generation, with vllm-omni specific extensions.
"""
import base64
import io
import uuid
import zipfile
from enum import Enum
from http import HTTPStatus
from typing import Any, Literal
from fastapi import HTTPException
from fastapi.responses import StreamingResponse
from pydantic import BaseModel, Field, field_validator
from vllm_omni.entrypoints.openai.image_api_utils import validate_layered_layers
@@ -20,6 +27,7 @@ class ResponseFormat(str, Enum):
B64_JSON = "b64_json"
URL = "url" # Not implemented in PoC
FILE = "file" # file response
class ImageGenerationRequest(BaseModel):
@@ -73,9 +81,9 @@ class ImageGenerationRequest(BaseModel):
@field_validator("response_format")
@classmethod
def validate_response_format(cls, v):
"""Validate response format - only b64_json is supported."""
if v is not None and v != ResponseFormat.B64_JSON:
raise ValueError(f"Only 'b64_json' response format is supported, got: {v}")
"""Validate response format - only b64_json and file are supported."""
if v is not None and v not in (ResponseFormat.B64_JSON, ResponseFormat.FILE):
raise ValueError(f"Only 'b64_json' or 'file' response format is supported, got: {v}")
return v
@field_validator("layers")
@@ -183,6 +191,40 @@ class ImageGenerationResponse(BaseModel):
"Only present for image editing (IT2I) with CoT-enabled models.",
)
def stream_response(self) -> StreamingResponse:
if not self.data or not self.data[0].b64_json:
raise HTTPException(
status_code=HTTPStatus.INTERNAL_SERVER_ERROR.value,
detail="No image data available for file response.",
)
if len(self.data) == 1:
image_bytes = base64.b64decode(self.data[0].b64_json)
filename = f"image_{uuid.uuid4().hex[:8]}.png"
return StreamingResponse(
io.BytesIO(image_bytes),
media_type="image/png",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Content-Length": str(len(image_bytes)),
},
)
else:
zip_buffer = io.BytesIO()
with zipfile.ZipFile(zip_buffer, "w", zipfile.ZIP_DEFLATED) as zf:
for idx, item in enumerate(self.data):
if item.b64_json:
zf.writestr(f"image_{idx}.png", base64.b64decode(item.b64_json))
zip_bytes = zip_buffer.getvalue()
filename = f"images_{uuid.uuid4().hex[:8]}.zip"
return StreamingResponse(
io.BytesIO(zip_bytes),
media_type="application/zip",
headers={
"Content-Disposition": f'attachment; filename="{filename}"',
"Content-Length": str(len(zip_bytes)),
},
)
class ImageEditARDeltaChunk(BaseModel):
"""Streaming chunk carrying a text delta from the image-edit AR stage."""