QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Qwen — Geração de imagem assíncrona (3.0 e 2.1-pro)

Geração assíncrona de imagens para o qwen-image-3.0 série e qwen-image-2.1-pro

Obtenha uma chave de API e defini-lo como uma variável de ambiente. Se estiver usando o SDK, instale-o.

Fluxo de trabalho

  1. Envie uma tarefa via POST /services/aigc/image-generation/generation com o X-DashScope-Async: enable cabeçalho.
  2. Enquete para resultados via GET /tasks/{task_id} até task_status alcança SUCCEEDED ou FAILED. Enquete a cada 10 segundos.

OpenAPI

openapi: 3.1.0
info:
  title: qwen-image-3.0 API
  description: qwen-image-3.0 text-to-image generation API. Supports synchronous calls for all models and asynchronous calls for legacy models.
  version: 1.0.0
servers:
  - url: https://maas.qwencloudapi.com/api/v1
    description: Singapore
security:
  - BearerAuth: []
paths:
  /services/aigc/image-generation/generation:
    post:
      operationId: createQwenImage30Async
      summary: Async image generation (3.0 and 2.1-pro)
      description: "Asynchronous invocation for the qwen-image-3.0 series and qwen-image-2.1-pro. Shares the same request structure as the synchronous endpoint — add the `X-DashScope-Async: enable` header, and the service returns a task ID (`task_id`) that you poll via the query endpoint for the final result."
      parameters:
        - name: X-DashScope-Async
          in: header
          required: true
          description: 'Must be set to `enable` for asynchronous task submission. Missing this header returns the error: "current user api does not support synchronous calls".'
          schema:
            type: string
            enum:
              - enable
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/QwenImage30AsyncRequest"
      responses:
        "200":
          description: Task submitted successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/AsyncTaskSubmitResponse"
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DashScopeErrorResponse"
      x-codeSamples:
        - lang: curl
          label: cURL (Submit task)
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/image-generation/generation' \
            --header 'Content-Type: application/json' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'X-DashScope-Async: enable' \
            --data '{
              "model": "qwen-image-3.0-pro",
              "input": {
                "messages": [
                  {
                    "role": "user",
                    "content": [
                      {
                        "text": "A healing-style hand-drawn poster featuring three puppies playing with a ball on lush green grass."
                      }
                    ]
                  }
                ]
              },
              "parameters": {
                "prompt_extend": true
              }
            }'
        - lang: curl
          label: cURL (Query result)
          source: |-
            # Replace {task_id} with the actual task ID returned by the submit step
            curl -X GET https://maas.qwencloudapi.com/api/v1/tasks/{task_id} \
              --header "Authorization: Bearer $DASHSCOPE_API_KEY"
        - lang: python
          label: Python (DashScope SDK)
          source: |
            from http import HTTPStatus
            from urllib.parse import urlparse, unquote
            from pathlib import PurePosixPath
            import requests
            import os
            import dashscope
            from dashscope import MultiModalConversation

            dashscope.base_http_api_url = 'https://maas.qwencloudapi.com/api/v1'

            prompt = ("A healing-style hand-drawn poster featuring three puppies "
                      "playing with a ball on lush green grass.")

            api_key = os.getenv("DASHSCOPE_API_KEY")

            messages = [
              {
                "role": "user",
                "content": [{"text": prompt}]
              }
            ]

            print('---Calling the API; please wait for the task to complete.---')
            response = MultiModalConversation.call(
              api_key=api_key,
              model="qwen-image-3.0-pro",
              messages=messages,
              result_format='message',
              stream=False,
              prompt_extend=True
            )

            if response.status_code == HTTPStatus.OK:
              content = response.output.choices[0].message.content
              for item in content:
                if 'image' in item:
                  image_url = item['image']
                  file_name = PurePosixPath(
                    unquote(urlparse(image_url).path)
                  ).parts[-1]
                  with open(f'./{file_name}', 'wb+') as f:
                    f.write(requests.get(image_url).content)
                  print(f"Image saved: {file_name}")
            else:
              print(f"Failed: {response.code}, {response.message}")
        - lang: java
          label: Java (DashScope SDK)
          source: |-
            import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
            import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
            import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
            import com.alibaba.dashscope.common.MultiModalMessage;
            import com.alibaba.dashscope.common.Role;
            import com.alibaba.dashscope.utils.Constants;
            import com.alibaba.dashscope.utils.JsonUtils;

            import java.util.*;

            public class QwenImage30Async {
              static {
                Constants.baseHttpApiUrl = "https://maas.qwencloudapi.com/api/v1";
              }

              static String apiKey = System.getenv("DASHSCOPE_API_KEY");

              public static void main(String[] args) throws Exception {
                String prompt = "A healing-style hand-drawn poster featuring three puppies "
                  + "playing with a ball on lush green grass.";

                MultiModalMessage userMessage = MultiModalMessage.builder()
                  .role(Role.USER.getValue())
                  .content(List.of(Map.of("text", prompt)))
                  .build();

                Map<String, Object> parameters = new HashMap<>();
                parameters.put("prompt_extend", true);

                MultiModalConversationParam param = MultiModalConversationParam.builder()
                  .apiKey(apiKey)
                  .model("qwen-image-3.0-pro")
                  .messages(List.of(userMessage))
                  .parameters(parameters)
                  .build();

                MultiModalConversation conversation = new MultiModalConversation();
                System.out.println("---Calling the API; please wait for the task to complete.---");
                MultiModalConversationResult result = conversation.call(param);
                System.out.println(JsonUtils.toJson(result));
              }
            }
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: DashScope API Key. Create one in the [QwenCloud console](https://home.qwencloud.com/api-keys).
  schemas:
    QwenImageSyncRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Model name.
          enum:
            - qwen-image-3.0-pro
            - qwen-image-3.0
            - qwen-image-2.1-pro
            - qwen-image-2.1-turbo
            - qwen-image-2.0-pro
            - qwen-image-2.0-pro-2026-06-22
            - qwen-image-2.0-pro-2026-04-22
            - qwen-image-2.0-pro-2026-03-03
            - qwen-image-2.0
            - qwen-image-2.0-2026-03-03
          example: qwen-image-3.0-pro
        input:
          type: object
          required:
            - messages
          description: Input data containing the messages array.
          properties:
            messages:
              type: array
              description: Single-turn only. Exactly one message with role `user`.
              minItems: 1
              maxItems: 1
              items:
                $ref: "#/components/schemas/QwenImageMessage"
        parameters:
          $ref: "#/components/schemas/QwenImageSyncParameters"
    QwenImageMessage:
      type: object
      required:
        - role
        - content
      properties:
        role:
          type: string
          enum:
            - user
          description: Must be `user`.
        content:
          type: array
          description: Message content array. Must contain exactly one text object.
          minItems: 1
          maxItems: 1
          items:
            $ref: "#/components/schemas/QwenImageContentPart"
    QwenImageContentPart:
      type: object
      required:
        - text
      properties:
        text:
          type: string
          description: Positive prompt describing the desired content, style, and composition. The qwen-image-3.0 series and qwen-image-2.1-pro accept up to 4,500 tokens (recommended maximum). The qwen-image-2.0 series accept up to 1,300 tokens. Other models accept up to 800 tokens. The system truncates excess tokens.
          example: A vertical outdoor portrait photograph. A dark blue sign in the upper left bears the large white blackletter words Il Messaggero, and below it the glass display window of a newsstand is filled with newspapers and magazine covers.
    QwenImageSyncParameters:
      type: object
      description: Image generation parameters.
      properties:
        negative_prompt:
          type: string
          description: Describes content you do NOT want in the image. Max 500 characters. Excess is auto-truncated. qwen-image-2.1-pro does not support this parameter.
          maxLength: 500
        size:
          type: string
          description: |-
            Output resolution as `width*height`.

            - **qwen-image-3.0 series and qwen-image-2.1-pro**: total pixels between 512\*512 and 2048\*2048, aspect ratio between 1:8 and 8:1; when omitted, the model auto-recommends a resolution based on the prompt.
            - **qwen-image-2.0 series**: total pixels between 512\*512 and 2048\*2048; default `2048*2048`.
          example: 2048*2048
        n:
          type: integer
          description: "Number of images to generate. All models supported by this operation allow 1-6 images. Default: 1."
          minimum: 1
          maximum: 6
          default: 1
        prompt_extend:
          type: boolean
          description: "Enable prompt rewriting. `true` (default): the model rewrites the prompt before generating; for the qwen-image-3.0 series and qwen-image-2.1-pro the rewriting follows the mode set by `prompt_extend_mode`. `false`: use your prompt as-is."
          default: true
        prompt_extend_mode:
          type: string
          description: |-
            Prompt rewriting mode. Supported by the qwen-image-3.0 series and qwen-image-2.1-pro only.

            - `direct` (default): direct prompt enhancement (DPE). Suitable for most scenarios.
            - `agent`: agent prompt enhancement (APE). Finer-grained rewriting; text-to-image only.
          enum:
            - direct
            - agent
          default: direct
        watermark:
          type: boolean
          description: 'Add a "Qwen-Image" watermark to the bottom-right corner. Default: `false`.'
          default: false
        enable_thinking:
          type: boolean
          description: "Enable thinking mode. Default: `true`. When enabled, the model enhances reasoning to improve image quality, but increases generation time. Only effective when `prompt_extend=true`. Supported for Direct T2I, Direct I2I, and Agent T2I; I2I Agent is not yet supported."
          default: true
        seed:
          type: integer
          description: "Random number seed. Range: [0, 2147483647]. Same seed produces more consistent (but not identical) results. If omitted, a random seed is used."
          minimum: 0
          maximum: 2147483647
    QwenImage30AsyncParameters:
      type: object
      description: Image generation parameters.
      properties:
        negative_prompt:
          type: string
          description: Describes content you do NOT want in the image. Max 500 characters. Excess is auto-truncated. Only qwen-image-3.0 series models support this parameter; qwen-image-2.1-pro does not.
          maxLength: 500
        size:
          type: string
          description: Output resolution as `width*height`. The qwen-image-3.0 series and qwen-image-2.1-pro support total pixels between 512\*512 and 2048\*2048 and an aspect ratio between 1:8 and 8:1; when omitted, the model auto-recommends a resolution based on the prompt.
          example: 2048*2048
        n:
          type: integer
          description: "Number of images to generate. All models supported by this operation allow 1-6 images. Default: 1."
          minimum: 1
          maximum: 6
          default: 1
        prompt_extend:
          type: boolean
          description: "Enable prompt rewriting. `true` (default): the model rewrites the prompt before generating; for the qwen-image-3.0 series and qwen-image-2.1-pro the rewriting follows the mode set by `prompt_extend_mode`. `false`: use your prompt as-is."
          default: true
        prompt_extend_mode:
          type: string
          description: |-
            Prompt rewriting mode. Supported by the qwen-image-3.0 series and qwen-image-2.1-pro only.

            - `direct` (default): direct prompt enhancement (DPE). Suitable for most scenarios.
            - `agent`: agent prompt enhancement (APE). Finer-grained rewriting; text-to-image only.
          enum:
            - direct
            - agent
          default: direct
        watermark:
          type: boolean
          description: 'Add a "Qwen-Image" watermark to the bottom-right corner. Default: `false`.'
          default: false
        enable_thinking:
          type: boolean
          description: "Enable thinking mode. Default: `true`. When enabled, the model enhances reasoning to improve image quality, but increases generation time. Only effective when `prompt_extend=true`. Supported for Direct T2I, Direct I2I, and Agent T2I; I2I Agent is not yet supported."
          default: true
        seed:
          type: integer
          description: "Random number seed. Range: [0, 2147483647]. Same seed produces more consistent (but not identical) results. If omitted, a random seed is used."
          minimum: 0
          maximum: 2147483647
    QwenImage30AsyncRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Model name.
          enum:
            - qwen-image-3.0-pro
            - qwen-image-3.0
            - qwen-image-2.1-pro
            - qwen-image-2.1-turbo
          example: qwen-image-3.0-pro
        input:
          type: object
          required:
            - messages
          description: Input data containing the messages array.
          properties:
            messages:
              type: array
              description: Request content array. Only single-turn conversations are supported; the array contains exactly one object.
              items:
                $ref: "#/components/schemas/QwenImageMessage"
        parameters:
          $ref: "#/components/schemas/QwenImage30AsyncParameters"
    QwenImageSyncResponse:
      type: object
      description: Synchronous qwen-image-3.0 generation response.
      example:
        output:
          choices:
            - finish_reason: stop
              message:
                content:
                  - image: https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx
                role: assistant
        usage:
          output_height: 2048
          output_width: 2048
          input_image_count: 0
          input_image_type: qima_input_2k
          output_image_count: 1
          output_image_type: qima_output_2k
        request_id: d0250a3d-b07f-49e1-bdc8-6793f4929xxx
      properties:
        output:
          type: object
          properties:
            choices:
              type: array
              description: List of generated results. Contains one element per generated image.
              items:
                $ref: "#/components/schemas/QwenImageChoice"
            task_metric:
              type: object
              description: Task result statistics. Not returned for qwen-image-2.0 and qwen-image-3.0 series.
              properties:
                TOTAL:
                  type: integer
                  description: Total number of tasks.
                SUCCEEDED:
                  type: integer
                  description: Number of successful tasks.
                FAILED:
                  type: integer
                  description: Number of failed tasks.
        usage:
          type: object
          description: "Usage statistics (successful results only). Fields vary by model series: the qwen-image-3.0 series returns the `output_*` / `input_*` fields; other series return `image_count` / `width` / `height`."
          properties:
            output_width:
              type: integer
              description: Width of the final output image, in pixels. Returned by the qwen-image-3.0 series only.
            output_height:
              type: integer
              description: Height of the final output image, in pixels. Returned by the qwen-image-3.0 series only.
            input_image_count:
              type: integer
              description: Number of input images in the request. 0 for text-to-image; the actual input count for image editing. Returned by the qwen-image-3.0 series only.
            input_image_type:
              type: string
              description: "Input image billing tier, determined by the output resolution pixel area: `qima_input_1k` when the area is 2,250,000 or less, `qima_input_2k` when greater. Returned by the qwen-image-3.0 series only."
            output_image_count:
              type: integer
              description: Number of output images actually returned. Returned by the qwen-image-3.0 series only.
            output_image_type:
              type: string
              description: "Output image billing tier, determined by the output resolution pixel area: `qima_output_1k` when the area is 2,250,000 or less, `qima_output_2k` when greater. Returned by the qwen-image-3.0 series only."
            image_count:
              type: integer
              description: Number of images generated. Not returned by the qwen-image-3.0 series, which uses `output_image_count` instead.
            width:
              type: integer
              description: Width of the generated image, in pixels. Not returned by the qwen-image-3.0 series, which uses `output_width` instead.
            height:
              type: integer
              description: Height of the generated image, in pixels. Not returned by the qwen-image-3.0 series, which uses `output_height` instead.
        request_id:
          type: string
          description: Unique request identifier for tracing and troubleshooting.
          example: abf1645b-b630-433a-92f6-xxxxxx
    QwenImageChoice:
      type: object
      properties:
        finish_reason:
          type: string
          description: "`stop` means normal completion."
          example: stop
        message:
          type: object
          properties:
            role:
              type: string
              description: Always `assistant`.
              enum:
                - assistant
            content:
              type: array
              description: Response content array.
              items:
                $ref: "#/components/schemas/QwenImageResponseContentPart"
    QwenImageResponseContentPart:
      type: object
      properties:
        image:
          type: string
          description: URL of the generated image (PNG). **Valid for 24 hours.** Download promptly.
    AsyncTaskSubmitResponse:
      type: object
      description: Response from an asynchronous task submission.
      example:
        output:
          task_status: PENDING
          task_id: 0385dc79-5ff8-4d82-bcb6-xxxxxx
        request_id: 4909100c-7b5a-9f92-bfe5-xxxxxx
      properties:
        request_id:
          type: string
          description: Unique request identifier.
        output:
          type: object
          properties:
            task_id:
              type: string
              description: Task ID for polling status. Use with `GET /tasks/{task_id}`.
            task_status:
              type: string
              description: Initial task status, typically `PENDING`.
              enum:
                - PENDING
                - RUNNING
                - SUCCEEDED
                - FAILED
                - CANCELED
                - UNKNOWN
    AsyncTaskStatusResponse:
      type: object
      description: Async task status and results.
      example:
        request_id: 7434edb2-3cba-44e6-a772-xxxxxx
        output:
          task_id: 878f591e-ebdf-4e45-97eb-xxxxxx
          task_status: SUCCEEDED
          submit_time: 2025-09-09 11:38:54.741
          scheduled_time: 2025-09-09 11:38:54.781
          end_time: 2025-09-09 11:39:19.484
          results:
            - orig_prompt: Healing-style hand-drawn poster...
              actual_prompt: Childhood-inspired hand-drawn poster design...
              url: https://dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com/7d/xxx.png?Expires=xxxx
        usage:
          image_count: 1
      properties:
        request_id:
          type: string
          description: Unique request identifier.
        output:
          type: object
          properties:
            task_id:
              type: string
              description: Task ID.
            task_status:
              type: string
              description: |-
                Current task status.

                - `PENDING`: Task is queued
                - `RUNNING`: Task is processing
                - `SUCCEEDED`: Task completed successfully
                - `FAILED`: Task failed
                - `CANCELED`: Task was canceled
                - `UNKNOWN`: Task does not exist or status is unknown
              enum:
                - PENDING
                - RUNNING
                - SUCCEEDED
                - FAILED
                - CANCELED
                - UNKNOWN
            submit_time:
              type: string
              description: Time when the task was submitted.
            scheduled_time:
              type: string
              description: Time when the task was scheduled for execution.
            end_time:
              type: string
              description: Time when the task completed.
            code:
              type: string
              description: Error code. Present when `task_status` is `FAILED`.
            message:
              type: string
              description: Error message. Present when `task_status` is `FAILED`.
            results:
              type: array
              description: Generated image results. Present when `task_status` is `SUCCEEDED`.
              items:
                $ref: "#/components/schemas/AsyncTaskResult"
            task_metrics:
              $ref: "#/components/schemas/TaskMetrics"
        usage:
          type: object
          description: Usage statistics.
          properties:
            image_count:
              type: integer
              description: Number of successfully generated images.
    AsyncTaskResult:
      type: object
      description: A single result from an async task.
      properties:
        orig_prompt:
          type: string
          description: The original prompt submitted by the user.
        actual_prompt:
          type: string
          description: The prompt actually used for generation (may differ from original if `prompt_extend` is enabled).
        url:
          type: string
          description: URL of the generated image. **Valid for 24 hours.**
    TaskMetrics:
      type: object
      description: Task completion metrics.
      properties:
        TOTAL:
          type: integer
          description: Total number of images requested.
        SUCCEEDED:
          type: integer
          description: Number of images successfully generated.
        FAILED:
          type: integer
          description: Number of images that failed to generate.
    DashScopeErrorResponse:
      type: object
      description: DashScope API error response.
      properties:
        request_id:
          type: string
          description: Unique request identifier.
        code:
          type: string
          description: Error code (e.g., `InvalidParameter`, `Throttling`, `Unauthorized`).
          example: InvalidParameter
        message:
          type: string
          description: Human-readable error message.
          example: num_images_per_prompt must be 1