设计与多媒体

Alibaba Cloud AI Image Qwen Image

基于 Model Studio DashScope SDK 调用 Qwen Image 系列模型生成图片

它能做什么

使用 DashScope Python SDK 调用 Model Studio 的 Qwen Image 系列模型生成图片,提供统一的 image.generate 接口,便于接入视频智能体流水线。脚本从响应中提取图片 URL 与宽高元数据,并写入本地输出目录。文档包含身份验证配置、参数说明、常见错误对照表,以及缓存、重试等运维建议。生成结果与至少一份 JSON 响应会一并保留作为证据。

什么时候用它

  • 为资产流水线批量生成产品图
  • 为视频生成工作流准备参考图
  • 使用固定 seed 与尺寸复现历史结果
  • 通过最小化只读请求验证 API 连通性

技能文档

Category: provider

Model Studio Qwen Image

Validation

mkdir -p output/alicloud-ai-image-qwen-image
python -m py_compile skills/ai/image/alicloud-ai-image-qwen-image/scripts/generate_image.py && echo "py_compile_ok" > output/alicloud-ai-image-qwen-image/validate.txt

Pass criteria: command exits 0 and output/alicloud-ai-image-qwen-image/validate.txt is generated.

Output And Evidence

  • Write generated image URLs, prompts, and metadata to output/alicloud-ai-image-qwen-image/.
  • Keep at least one sample JSON response per run.

Build consistent image generation behavior for the video-agent pipeline by standardizing image.generate inputs/outputs and using DashScope SDK (Python) with the exact model name.

Prerequisites

  • Install SDK (recommended in a venv to avoid PEP 668 limits):
python3 -m venv .venv
. .venv/bin/activate
python -m pip install dashscope
  • Set DASHSCOPE_API_KEY in your environment, or add dashscope_api_key to ~/.alibabacloud/credentials (env takes precedence).

Critical model names

Use one of these exact model strings:

  • qwen-image
  • qwen-image-plus
  • qwen-image-max
  • qwen-image-2.0
  • qwen-image-2.0-pro
  • qwen-image-max-2025-12-30
  • qwen-image-plus-2026-01-09

Normalized interface (image.generate)

Request

  • prompt (string, required)
  • negative_prompt (string, optional)
  • size (string, required) e.g. 1024*1024, 768*1024
  • style (string, optional)
  • seed (int, optional)
  • reference_image (string | bytes, optional)

Response

  • image_url (string)
  • width (int)
  • height (int)
  • seed (int)

Quickstart (normalized request + preview)

Minimal normalized request body:

{
  "prompt": "a cinematic portrait of a cyclist at dusk, soft rim light, shallow depth of field",
  "negative_prompt": "blurry, low quality, watermark",
  "size": "1024*1024",
  "seed": 1234
}

Preview workflow (download then open):

curl -L -o output/alicloud-ai-image-qwen-image/images/preview.png "" && open output/alicloud-ai-image-qwen-image/images/preview.png

Local helper script (JSON request -> image file):

python skills/ai/image/alicloud-ai-image-qwen-image/scripts/generate_image.py \\
  --request '{"prompt":"a studio product photo of headphones","size":"1024*1024"}' \\
  --output output/alicloud-ai-image-qwen-image/images/headphones.png \\
  --print-response

Parameters at a glance

FieldRequiredNotes
promptyesDescribe a scene, not just keywords.
negative_promptnoBest-effort, may be ignored by backend.
sizeyesWxH format, e.g. 1024*1024, 768*1024.
stylenoOptional stylistic hint.
seednoUse for reproducibility when supported.
reference_imagenoURL/file/bytes, SDK-specific mapping.

Quick start (Python + DashScope SDK)

Use the DashScope SDK and map the normalized request into the SDK call. Note: For qwen-image-max, the DashScope SDK currently succeeds via ImageGeneration (messages-based) rather than ImageSynthesis. If the SDK version you are using expects a different field name for reference images, adapt the input mapping accordingly.

import os
from dashscope.aigc.image_generation import ImageGeneration

# Prefer env var for auth: export DASHSCOPE_API_KEY=...
# Or use ~/.alibabacloud/credentials with dashscope_api_key under [default].


def generate_image(req: dict) -> dict:
    messages = [
        {
            "role": "user",
            "content": [{"text": req["prompt"]}],
        }
    ]

    if req.get("reference_image"):
        # Some SDK versions accept {"image": } in messages content.
        messages[0]["content"].insert(0, {"image": req["reference_image"]})

    response = ImageGeneration.call(
        model=req.get("model", "qwen-image-max"),
        messages=messages,
        size=req.get("size", "1024*1024"),
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # Pass through optional parameters if supported by the backend.
        negative_prompt=req.get("negative_prompt"),
        style=req.get("style"),
        seed=req.get("seed"),
    )

    # Response is a generation-style envelope; extract the first image URL.
    content = response.output["choices"][0]["message"]["content"]
    image_url = None
    for item in content:
        if isinstance(item, dict) and item.get("image"):
            image_url = item["image"]
            break
    return {
        "image_url": image_url,
        "width": response.usage.get("width"),
        "height": response.usage.get("height"),
        "seed": req.get("seed"),
    }

Error handling

ErrorLikely causeAction
401/403Missing or invalid DASHSCOPE_API_KEYCheck env var or ~/.alibabacloud/credentials, and access policy.
400Unsupported size or bad request shapeUse common WxH and validate fields.
429Rate limit or quotaRetry with backoff, or reduce concurrency.
5xxTransient backend errorsRetry with backoff once or twice.

Output location

  • Default output: output/alicloud-ai-image-qwen-image/images/
  • Override base dir with OUTPUT_DIR.

Operational guidance

  • Store the returned image in object storage and persist only the URL in metadata.
  • Cache results by (prompt, negative_prompt, size, seed, reference_image hash) to avoid duplicate costs.
  • Add retries for transient 429/5xx responses with exponential backoff.
  • Some backends ignore negative_prompt, style, or seed; treat them as best-effort inputs.
  • If the response contains no image URL, surface a clear error and retry once with a simplified prompt.

Size notes

  • Use WxH format (e.g. 1024*1024, 768*1024).
  • Prefer common sizes; unsupported sizes can return 400.

Anti-patterns

  • Do not invent model names or aliases; use official model IDs only.
  • Do not store large base64 blobs in DB rows; use object storage.
  • Do not omit user-visible progress for long generations.

Workflow

  1. Confirm user intent, region, identifiers, and whether the operation is read-only or mutating.
  2. Run one minimal read-only query first to verify connectivity and permissions.
  3. Execute the target operation with explicit parameters and bounded scope.
  4. Verify results and save output/evidence files.

References

  • See references/api_reference.md for a more detailed DashScope SDK mapping and response parsing tips.

  • See references/prompt-guide.md for prompt patterns and examples.

  • For edit workflows, use skills/ai/image/alicloud-ai-image-qwen-image-edit/.

  • Source list: references/sources.md

常见问题

支持哪些 Qwen Image 模型?
文档列出的精确型号包括 qwen-image、qwen-image-plus、qwen-image-max、qwen-image-2.0、qwen-image-2.0-pro、qwen-image-max-2025-12-30 和 qwen-image-plus-2026-01-09,并明确要求不要自造别名。
如何配置认证信息?
优先设置环境变量 DASHSCOPE_API_KEY;也可以在 ~/.alibabacloud/credentials 的 [default] 段写入 dashscope_api_key,环境变量优先级更高。
生成结果和证据文件保存到哪里?
默认写入 output/alicloud-ai-image-qwen-image/,图片放在 images/ 子目录。可通过 OUTPUT_DIR 覆盖根目录;每次运行会保留至少一份 JSON 响应作为证据。

相关技能

Edit images with Alibaba Cloud Model Studio Qwen Image Edit models (qwen-image-edit, qwen-image-edit-plus, qwen-image-edit-max and snapshots). Use when modif...

54 次安装

Generate human-like speech audio with Model Studio DashScope Qwen TTS models (qwen3-tts-flash, qwen3-tts-instruct-flash). Use when converting text to speech,...

66 次安装

Route Alibaba Cloud Model Studio requests to the right local skill (Qwen Image, Qwen Image Edit, Wan Video, Wan R2V, Qwen TTS, Qwen ASR and advanced TTS vari...

60 次安装

Generate videos with Model Studio DashScope SDK using Wan i2v models (wan2.6-i2v-flash, wan2.6-i2v, wan2.6-i2v-us). Use when implementing or documenting vide...

65 次安装

Generate images with Alibaba Cloud Model Studio Z-Image Turbo (z-image-turbo) via DashScope multimodal-generation API. Use when creating text-to-image output...

62 次安装

通过单一脚本调用多家官方图像生成 API,支持参考图与批量并发。

156 次安装1 星标