ARTICLE DETAIL

资讯详情

深耕郑州网站建设与运营推广的一线实战洞察。

vLLM-Omni 图像生成 API 实战指南:OpenAI DALL-E 兼容的文生图接口 /v1/images/generations 详解

vLLM-Omni 图像生成 API 实战指南:OpenAI DALL-E 兼容的文生图接口 /v1/images/generations 详解 vLLM-Omni 图像生成 API 实战指南OpenAI DALL-E 兼容的文生图接口 /v1/images/generations 详解【免费下载链接】vllm-omniA framework for efficient model inference with omni-modality models项目地址: https://gitcode.com/GitHub_Trending/vl/vllm-omni本文基于仓库文档 docs/serving/image_generation_api.md讲解 vLLM-Omni 提供的 OpenAI DALL-E 兼容文本生图 API如何启动服务、如何用 curl/Python/OpenAI SDK 调用POST /v1/images/generations、全部请求参数含 vllm-omni 扩展参数的取值与默认值、响应格式与错误码语义并结合 协议定义 与 路由处理实现 深入到请求校验、参数透传与文件流式返回的源码级原理。读完后你可以直接把扩散模型以标准 OpenAI 图像 API 的形式接入现有应用。快速上手启动服务每个服务实例只运行一个模型启动时通过vllm serve model --omni指定--omni标志的定义与参数校验见 CLI serve 入口# Qwen-Image vllm serve Qwen/Qwen-Image --omni --port 8000 # Z-Image Turbo vllm serve Tongyi-MAI/Z-Image-Turbo --omni --port 8000从源码结构看--omni模式下 CLI 会以uvloop.run(omni_run_server(args))启动 OpenAI 兼容服务器模型必须显式给出否则参数解析阶段就会报错。生成图像curl 方式返回 base64 并解码保存curl -X POST http://localhost:8000/v1/images/generations \ -H Content-Type: application/json \ -d { prompt: a dragon laying over the spine of the Green Mountains of Vermont, size: 1024x1024, seed: 42 } | jq -r .data[0].b64_json | base64 -d dragon.pngcurl 方式服务端直接以文件流返回curl -o dragon.png -X POST http://localhost:8000/v1/images/generations \ -H Content-Type: application/json \ -d { prompt: a dragon laying over the spine of the Green Mountains of Vermont, size: 1024x1024, seed: 42, response_format:file }Pythonrequests方式import requests import base64 from PIL import Image import io response requests.post( http://localhost:8000/v1/images/generations, json{ prompt: a black and white cat wearing a princess tiara, size: 1024x1024, num_inference_steps: 50, seed: 42, } ) # Decode and save img_data response.json()[data][0][b64_json] img_bytes base64.b64decode(img_data) img Image.open(io.BytesIO(img_bytes)) img.save(cat.png)Python 文件流方式response_format: fileimport requests import base64 from PIL import Image import io import re response requests.post( http://localhost:8000/v1/images/generations, json{ prompt: a black and white cat wearing a princess tiara, size: 1024x1024, num_inference_steps: 50, seed: 42, response_format:file } ) # save to file content_disposition response.headers.get(Content-Disposition, ) match re.search(rfilename?(.)?, content_disposition) filename match.group(1) if match else save.png with open(filename, wb) as f: for chunk in response.iter_content(8192): f.write(chunk) print(saved:, filename)OpenAI SDK 方式from openai import OpenAI client OpenAI(base_urlhttp://localhost:8000/v1, api_keynone) response client.images.generate( modelQwen/Qwen-Image, prompta horse jumping over a fence nearby a babbling brook, n1, size1024x1024, response_formatb64_json ) # Note: Extension parameters (seed, steps, cfg) require direct HTTP requests注意 OpenAI SDK 的images.generate只接受标准字段seed、num_inference_steps、guidance_scale等 vllm-omni 扩展参数需要通过直接 HTTP 请求或 SDK 的extra_body机制传递。API 参考端点POST /v1/images/generations Content-Type: application/json路由注册在 api_server.py 的generate_images处理器中声明了 200/400/503/500 四种响应模型并用with_cancellation装饰器支持请求取消。请求参数OpenAI 标准参数参数类型默认值说明promptstring必填期望生成图像的文字描述modelstring服务端模型要使用的模型可选若指定必须与服务端运行模型一致否则返回 400ninteger1生成图像数量1–10sizestring模型默认图像尺寸WIDTHxHEIGHT格式如 1024x1024、512x512response_formatstringb64_json响应格式b64_json 或 fileuserstringnull用于追踪的用户标识源码中对应的 Pydantic 模型 ImageGenerationRequest 定义了严格的字段约束n通过Field(default1, ge1, le10)限制在 1–10size有字段校验器接受任意WIDTHxHEIGHT字符串不限制具体分辨率但字符串中必须包含 x否则校验失败这就是文档示例中 400 错误Invalid size format: 1024x的来源response_format枚举定义支持b64_json、url、file三种取值但校验器明确拒绝url——当前仅支持b64_json与fileurl在代码注释中标注为 Not implemented in PoC。vllm-omni 扩展参数原文档列出的核心五个参数类型默认值说明negative_promptstringnull描述图像中要避免的内容num_inference_stepsinteger模型默认扩散采样步数guidance_scalefloat模型默认Classifier-free guidance 强度通常 0.0–20.0true_cfg_scalefloat模型默认True CFG 强度模型相关参数不支持时可能被忽略seedintegernull随机种子保证结果可复现结合 协议定义源码还可以确认这些参数的精确取值边界以及官方文档未逐一列出但实际可用的扩展字段参数类型取值范围/默认说明num_inference_stepsinteger1–200扩散采样步数ge1, le200guidance_scalefloat0.0–20.0CFG 引导强度true_cfg_scalefloat0.0–20.0True CFG 强度seedintegerint64 范围随机种子服务端在未提供时会补一个随机值见下文参数透传flow_shiftfloat无上下界flow-matching 类扩散模型的调度器 sigma shiftextra_paramsdictnull直接透传给模型extra_args的模型专属参数generator_devicestringrunner 设备带种子的torch.Generator所在设备如 cpu、cudaloradictnull按请求加载 LoRA 适配器形如{name/path/scale/int_id}字段名兼容lora_name、adapter、local_path等变体vae_use_slicing/vae_use_tilingboolfalseVAE 显存优化开关在模型初始化时设定output_formatstringpng输出图像格式png、jpeg、webpoutput_compressioninteger100压缩等级 0–100对 png 而言 100 对应最快编码较低值以编码时间换更小体积layersintegernull分层图像模型的输出层数2–10仅分层模型支持return_stage_metricsboolnull在响应metrics字段中返回每阶段耗时等指标供压测客户端使用响应格式b64_json默认模式下返回 JSON{ created: 1701234567, data: [ { b64_json: base64-encoded PNG, url: null, revised_prompt: null } ] }从源码 ImageGenerationResponse 看响应体除created和data外还带有output_format实际输出格式、size回显请求尺寸与可选的metrics含stage_durations各阶段耗时与peak_memory_mb峰值显存其中metrics仅在请求中传入return_stage_metrics: true时才会填充完整指标。file模式下服务端不再返回 JSON而是直接输出二进制流单张图像以Content-Disposition: attachment; filenameimage_8位随机hex.ext流式返回media_type按output_format映射为image/png、image/jpeg或image/webp并带Content-Length多张图像打包成images_8位随机hex.zipapplication/zip流式返回内部文件命名为image_0.png、image_1.png……流按 64KB 分块_FILE_RESPONSE_CHUNK_SIZE 64 * 1024发送避免大图一次性占用响应内存。实现见 stream_response。示例一次生成多张图像curl -X POST http://localhost:8000/v1/images/generations \ -H Content-Type: application/json \ -d { prompt: a steampunk city set in a valley of the Adirondack mountains, n: 4, size: 1024x1024, seed: 123 }单次请求生成 4 张图像配合response_format: file时会自动打包为 zip 返回。使用负面提示词response requests.post( http://localhost:8000/v1/images/generations, json{ prompt: a portrait of a skier in deep powder snow, negative_prompt: blurry, low quality, distorted, ugly, num_inference_steps: 100, size: 1024x1024, } )参数处理机制透传设计的源码解析官方文档强调API 将参数直接传给扩散 pipeline不做模型特定转换。这一点可以从 generate_images 处理函数 中逐行验证默认值未指定的参数不写入OmniDiffusionSamplingParams——代码通过_update_if_not_none(gen_params, num_inference_steps, request.num_inference_steps)这类非空才设置的辅助函数逐个填充未设置字段保持为 None由底层扩散引擎回落到模型自身默认值透传设计guidance_scale、true_cfg_scale、flow_shift、extra_params等字段一旦被提供就原样转发到扩散引擎API 层不做模型特定的参数重映射最小校验API 层只保留类型检查Pydantic 字段约束和范围校验如num_inference_steps1–200尺寸解析由 parse_size 完成格式非法即抛 400。几个值得注意的实现细节随机种子的自动补全即使请求没有seed服务端也会生成一个random.randint(0, MAX_UINT32_SEED)的随机种子传给后端api_server.py。源码注释说明这是为了在部分环境下避免使用全局默认 Generator 导致图像模糊的问题尺寸上限检查当服务端配置了--max-generated-image-size时helpers 中的 _check_max_generated_image_size 会校验width * height是否超限超限直接返回 400并提示调小尺寸或调高服务端上限多阶段管线分支当部署为多阶段AR 扩散管线时len(stage_configs) 1请求不再走单阶段采样参数路径而是把seed、n、size、negative_prompt等统一装进extra_body复用与/v1/chat/completions相同的openai_serving_chat.generate_diffusion_images构建逻辑api_server.py保证两个入口的行为一致模型名校验请求中的model若与服务端运行模型不一致立即返回 400Model mismatch: request specifies ... but server is running ....结果归一化扩散引擎返回的图像PIL 或 numpy 数组在 helpers.py 的 _extract_images_from_result / _normalize_image 中统一转为 PIL 图像浮点张量会做 [-1,1]/[0,1] 范围裁剪再量化为 uint8。参数兼容性API 不对参数做模型级验证因此不支持的参数可能被模型静默忽略不兼容的取值会导致底层 pipeline 报错最终以 400/500 返回推荐取值因模型而异——建议以各模型文档例如仓库 recipes 目录下对应模型的接入文档中的推荐参数为起点再调整。最佳实践先使用模型推荐参数再按需求微调。错误响应400 Bad Request参数非法如模型不匹配、尺寸格式错误、超出尺寸上限{ detail: Invalid size format: 1024x. Expected format: WIDTHxHEIGHT (e.g., 1024x1024). }422 Unprocessable EntityPydantic 校验错误缺少必填字段等FastAPI 标准校验响应{ detail: [ { loc: [body, prompt], msg: field required, type: value_error.missing } ] }503 Service Unavailable扩散引擎未初始化{ detail: Diffusion engine not initialized. Start server with a diffusion model. }此外路由注册中声明了 500INTERNAL_SERVER_ERROR响应模型EngineGenerateError/EngineDeadError会被_create_engine_error_json_response统一转换为引擎错误 JSON 响应而非裸 500。故障排查服务未响应# Check if server is responding curl http://localhost:8000/v1/images/generations \ -H Content-Type: application/json \ -d {prompt: test}也可以先用GET /health检查引擎存活状态health 端点 在引擎未初始化或EngineDeadError时返回 503健康时返回{status: healthy}。显存不足OOM遇到 OOM 时按优先级尝试降低图像尺寸size: 512x512降低推理步数num_inference_steps: 25减少生成数量n: 1。测试与调试运行测试套件# All image generation tests pytest tests/entrypoints/openai_api/test_image_server.py -v # Specific test pytest tests/entrypoints/openai_api/test_image_server.py::test_generate_single_image -vtests/entrypoints/openai_api/test_image_server.py 覆盖了尺寸解析test_parse_size_valid/invalid/negative/edge_cases、单张/多张生成test_generate_single_image、test_generate_multiple_images、负面提示词test_with_negative_prompt、超限尺寸拒绝test_generate_images_max_size_rejected以及多阶段管线构造test_multistage_images_async_omni_construction等场景可用于回归验证本接口的行为。协议层字段约束另有 tests/entrypoints/openai_api/test_image_protocol.py 专门测试。开启调试日志vllm serve Qwen/Qwen-Image --omni \ --uvicorn-log-level debug调试日志中可以看到 prompt 与生成的详细信息例如处理函数中的logger.debug(fGenerating {request.n} image(s) {size_str})会打印请求数量与尺寸便于排查参数是否按预期到达服务端。适用前提与限制小结每个服务端实例只加载一个模型模型在vllm serve model --omni启动时确定请求中不能切换模型当前版本仅支持b64_json与file两种响应格式url模式未实现num_inference_steps1–200、guidance_scale/true_cfg_scale0–20等边界由 API 层强制执行超出即拒绝多张图像 file格式时返回的是 zip 压缩包而非多张独立图片客户端需自行解包本接口的参数透传设计意味着能提交不等于模型支持落地到具体模型Qwen-Image、Z-Image-Turbo 等前建议先查阅 recipes 下对应模型的接入文档确认推荐参数。【免费下载链接】vllm-omniA framework for efficient model inference with omni-modality models项目地址: https://gitcode.com/GitHub_Trending/vl/vllm-omni创作声明:本文部分内容由AI辅助生成(AIGC),仅供参考
返回列表