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

Wan 2.6 síncrono

Síncrono Wan 2.6 geração e edição de imagens

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

Este endpoint síncrono é para wan2.6-image apenas. Recupere imagens geradas diretamente em uma única solicitação, sem pesquisa.

Para processamento assíncrono, use o async submit ponto final.

OpenAPI

openapi: 3.1.0
info:
  title: Wan2.6 Image Generation and Editing API
  description: Wan2.6 image generation and editing API. Supports multi-image input, image editing, and interleaved text-image output.
  version: 1.0.0
servers:
  - url: https://maas.qwencloudapi.com/api/v1
    description: Singapore
security:
  - BearerAuth: []
paths:
  /services/aigc/multimodal-generation/generation:
    post:
      operationId: createWan26Image
      summary: Generate or edit images synchronously
      description: Generate or edit images synchronously using Wan2.6.
      requestBody:
        required: true
        content:
          application/json:
            schema:
              $ref: "#/components/schemas/Wan26ImageRequest"
      responses:
        "200":
          description: Image generated or edited successfully
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/Wan26ImageResponse"
        "400":
          description: Invalid request parameters
          content:
            application/json:
              schema:
                $ref: "#/components/schemas/DashScopeErrorResponse"
      x-codeSamples:
        - lang: curl
          label: cURL (image editing)
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/multimodal-generation/generation' \
            --header 'Content-Type: application/json' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --data '{
              "model": "wan2.6-image",
              "input": {
                "messages": [
                  {
                    "role": "user",
                    "content": [
                      {
                        "text": "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"
                      },
                      {
                        "image": "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"
                      },
                      {
                        "image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
                      }
                    ]
                  }
                ]
              },
              "parameters": {
                "prompt_extend": true,
                "watermark": false,
                "n": 1,
                "enable_interleave": false,
                "size": "1K"
              }
            }'
        - lang: curl
          label: cURL (interleaved text-image, streaming)
          source: |-
            curl --location 'https://maas.qwencloudapi.com/api/v1/services/aigc/multimodal-generation/generation' \
            --header 'Content-Type: application/json' \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
            --header 'X-DashScope-Sse: enable' \
            --data '{
              "model": "wan2.6-image",
              "input": {
                "messages": [
                  {
                    "role": "user",
                    "content": [
                      {
                        "text": "Give me a three-image tutorial for stir-fried pork with chili peppers"
                      }
                    ]
                  }
                ]
              },
              "parameters": {
                "max_images": 3,
                "size": "1280*1280",
                "stream": true,
                "enable_interleave": true
              }
            }'
        - lang: python
          label: Python - image editing (sync)
          source: |-
            import os
            import dashscope
            from dashscope.aigc.image_generation import ImageGeneration
            from dashscope.api_entities.dashscope_response import Message

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

            api_key = os.getenv("DASHSCOPE_API_KEY")

            message = Message(
              role="user",
              # Supports local files, e.g., "image": "file://umbrella1.png"
              content=[
                {
                  "text": "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"
                },
                {
                  "image": "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"
                },
                {
                  "image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
                }
              ]
            )
            print("----sync call, wait a moment----")
            rsp = ImageGeneration.call(
                model='wan2.6-image',
                api_key=api_key,
                messages=[message],
                negative_prompt="",
                prompt_extend=True,
                watermark=False,
                n=1,
                enable_interleave=False,
                size="1K"
              )

            print(rsp)
        - lang: python
          label: Python - interleaved text-image (streaming)
          source: |-
            import os
            import dashscope
            from dashscope.aigc.image_generation import ImageGeneration
            from dashscope.api_entities.dashscope_response import Message

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

            api_key = os.getenv("DASHSCOPE_API_KEY")

            def sync_call_with_stream():
              print("\n========== Synchronous call - Streaming text-image output ==========")

              image_message = Message(
                role="user",
                content=[
                  {
                    "text": "Give me a three-image tutorial for stir-fried pork with chili peppers"
                  }
                ]
              )

              image_stream_res = ImageGeneration.call(
                model="wan2.6-image",
                api_key=api_key,
                messages=[image_message],
                stream=True,  # Streaming only
                negative_prompt="",
                enable_interleave=True,
                max_images=3,
                size="1280*1280"
              )

              print("Streaming output results:")
              for stream_res in image_stream_res:
                print(stream_res)

            if __name__ == "__main__":
              sync_call_with_stream()
        - lang: java
          label: Java - image editing (sync)
          source: |-
            import com.alibaba.dashscope.aigc.imagegeneration.*;
            import com.alibaba.dashscope.exception.ApiException;
            import com.alibaba.dashscope.exception.NoApiKeyException;
            import com.alibaba.dashscope.exception.UploadFileException;
            import com.alibaba.dashscope.utils.Constants;
            import com.alibaba.dashscope.utils.JsonUtils;

            import java.util.Arrays;
            import java.util.Collections;

            /**
             * wan2.6-image Image editing - Synchronous call example
             */
            public class Main {

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

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

                public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
                    // Build multi-image input message
                    ImageGenerationMessage message = ImageGenerationMessage.builder()
                            .role("user")
                            .content(Arrays.asList(
                                    Collections.singletonMap("text", "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"),
                                    Collections.singletonMap("image", "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"),
                                    Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp")
                            )).build();

                    ImageGenerationParam param = ImageGenerationParam.builder()
                            .apiKey(apiKey)
                            .model("wan2.6-image")
                            .messages(Collections.singletonList(message))
                            .n(1)
                            .size("1K")
                            .negativePrompt("")
                            .promptExtend(true)
                            .build();

                    ImageGeneration imageGeneration = new ImageGeneration();
                    ImageGenerationResult result = null;
                    try {
                        System.out.println("---sync call for image editing, wait a moment----");
                        result = imageGeneration.call(param);
                    } catch (ApiException | NoApiKeyException | UploadFileException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                    System.out.println(JsonUtils.toJson(result));
                }

                public static void main(String[] args) {
                    try {
                        basicCall();
                    } catch (ApiException | NoApiKeyException | UploadFileException e) {
                        System.out.println(e.getMessage());
                    }
                }
            }
        - lang: java
          label: Java - interleaved text-image (streaming)
          source: |-
            import com.alibaba.dashscope.aigc.imagegeneration.*;
            import com.alibaba.dashscope.exception.ApiException;
            import com.alibaba.dashscope.exception.NoApiKeyException;
            import com.alibaba.dashscope.exception.UploadFileException;
            import com.alibaba.dashscope.utils.Constants;
            import com.alibaba.dashscope.utils.JsonUtils;
            import io.reactivex.Flowable;

            import java.util.Collections;

            /**
             * wan2.6-image Text-image output - Streaming call example
             */
            public class Main {

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

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

                public static void streamCall() throws ApiException, NoApiKeyException, UploadFileException {
                    ImageGenerationMessage message = ImageGenerationMessage.builder()
                            .role("user")
                            .content(Collections.singletonList(
                                    Collections.singletonMap("text", "Give me a three-image tutorial for stir-fried pork with chili peppers")
                            )).build();

                    // Text-image output requires streaming call
                    ImageGenerationParam param = ImageGenerationParam.builder()
                            .apiKey(apiKey)
                            .model("wan2.6-image")
                            .messages(Collections.singletonList(message))
                            .stream(true) // Must enable streaming output
                            .enableInterleave(true)
                            .size("1280*1280")
                            .negativePrompt("")
                            .maxImages(3)
                            .build();

                    ImageGeneration imageGeneration = new ImageGeneration();
                    try {
                        System.out.println("---stream call for image interleave----");
                        Flowable<ImageGenerationResult> resultFlowable = imageGeneration.streamCall(param);
                        resultFlowable.blockingForEach(result -> {
                            System.out.println(JsonUtils.toJson(result));
                        });
                    } catch (ApiException | NoApiKeyException | UploadFileException e) {
                        throw new RuntimeException(e.getMessage());
                    }
                }

                public static void main(String[] args) {
                    try {
                        streamCall();
                    } catch (ApiException | NoApiKeyException | UploadFileException e) {
                        System.out.println(e.getMessage());
                    }
                    System.exit(0);
                }
            }
components:
  securitySchemes:
    BearerAuth:
      type: http
      scheme: bearer
      description: DashScope API Key. Create one in the [QwenCloud console](https://home.qwencloud.com/api-keys).
  schemas:
    Wan26ImageRequest:
      type: object
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Model name. Set to `wan2.6-image`.
          enum:
            - wan2.6-image
          example: wan2.6-image
        input:
          type: object
          required:
            - messages
          description: Input data containing the messages array.
          properties:
            messages:
              type: array
              description: "Array of request content. Only single-turn conversations are supported. Provide one message with `role: user`."
              minItems: 1
              maxItems: 1
              items:
                $ref: "#/components/schemas/Wan26ImageMessage"
        parameters:
          $ref: "#/components/schemas/Wan26ImageParameters"
    Wan26ImageMessage:
      type: object
      required:
        - role
        - content
      properties:
        role:
          type: string
          enum:
            - user
          description: Message role. Must be `user`.
        content:
          type: array
          description: |-
            Message content array. Must contain exactly one `text` object. Image objects depend on the mode:
            - Image editing (`enable_interleave=false`): **1 to 4** image objects required.
            - Interleaved text-image (`enable_interleave=true`): **0 to 1** image objects.

            When using multiple images, include multiple `image` objects in the array. Image order is determined by array position.
          items:
            $ref: "#/components/schemas/Wan26ImageContentPart"
    Wan26ImageContentPart:
      type: object
      description: Either an image or text content part.
      properties:
        text:
          type: string
          description: Positive prompt describing the desired image content, style, and composition. Supports Chinese and English. Maximum 2,000 characters (each Chinese character, letter, digit, or symbol counts as one character). Excess is auto-truncated. The `content` array must contain exactly one `text` object.
          maxLength: 2000
          example: Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2
        image:
          type: string
          description: |-
            Input image as a public URL (HTTP/HTTPS) or Base64-encoded string (`data:{mime_type};base64,{data}`).

            **Image constraints:**
            - Formats: JPEG, JPG, PNG (alpha channel not supported), BMP, WEBP.
            - Resolution: Width and height each between 240 and 8,000 pixels.
            - File size: Max 10 MB.

            **Image quantity limits:**
            - When `enable_interleave=false` (image editing): must input 1 to 4 images.
            - When `enable_interleave=true` (interleaved text-image): can input 0 to 1 images.
          example: https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png
    Wan26ImageParameters:
      type: object
      description: Image processing parameters.
      properties:
        negative_prompt:
          type: string
          description: |-
            Negative prompt describing content you do NOT want in the image. Supports Chinese and English. Maximum 500 characters. Excess is auto-truncated.

            Example: `Low resolution, low quality, deformed limbs, deformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth skin, AI-looking artifacts, chaotic composition, blurry or distorted text.`
          maxLength: 500
        size:
          type: string
          description: |-
            Output image resolution. Supports two methods: referencing input image proportions or directly specifying dimensions.

            **Image editing mode** (`enable_interleave=false`):
            - Method 1 (recommended): `1K` (default) or `2K`. Output total pixels close to 1280\*1280 or 2048\*2048, maintaining the aspect ratio of the last input image.
            - Method 2: Specify `width*height` in pixels. Total pixels must be between [768\*768, 2048\*2048], aspect ratio [1:4, 4:1]. Actual values are multiples of 16.

            **Interleaved text-image mode** (`enable_interleave=true`):
            - Method 1 (default): References input image proportions. If total pixels <= 1280\*1280, output matches input. If > 1280\*1280, output scales to ~1280\*1280.
            - Method 2: Specify `width*height`. Total pixels must be between [768\*768, 1280\*1280], aspect ratio [1:4, 4:1].

            **Recommended resolutions:** 1280\*1280 (1:1), 800\*1200 (2:3), 1200\*800 (3:2), 960\*1280 (3:4), 1280\*960 (4:3), 720\*1280 (9:16), 1280\*720 (16:9), 1344\*576 (21:9).
          example: 1K
        enable_interleave:
          type: boolean
          description: |-
            Controls image generation mode:
            - `false` (default): Image editing mode. Supports multi-image input (1-4 images) and subject consistency generation. Can generate 1 to 4 result images.
            - `true`: Interleaved text-image output mode. Supports 0-1 input images. Generates mixed content containing both text and images. **Requires** `stream=true` and `X-DashScope-Sse: enable` header.
          default: false
        n:
          type: integer
          description: |-
            Number of images to generate. Behavior depends on mode:
            - Image editing (`enable_interleave=false`): Range 1-4. Default: 4.
            - Interleaved text-image (`enable_interleave=true`): Must be 1. Use `max_images` to control image count instead.

            **Note:** `n` directly affects cost. Cost = unit price x number of successfully generated images.
          minimum: 1
          maximum: 4
          default: 4
        max_images:
          type: integer
          description: |-
            Only effective in interleaved text-image mode (`enable_interleave=true`). Specifies the maximum number of images the model can generate in a single response. Range: 1-5. Default: 5. The actual number of generated images is determined by model inference and may be less than this value.

            **Note:** `max_images` affects cost. Cost = unit price x number of successfully generated images.
          minimum: 1
          maximum: 5
          default: 5
        prompt_extend:
          type: boolean
          description: Only effective in image editing mode (`enable_interleave=false`). Enables intelligent prompt rewriting that optimizes and refines the positive prompt. The negative prompt is not affected.
          default: true
        stream:
          type: boolean
          description: Controls whether the response uses streaming output. In interleaved text-image mode (`enable_interleave=true`), you **must** set this to `true`.
          default: false
        watermark:
          type: boolean
          description: Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated".
          default: false
        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
    Wan26ImageResponse:
      type: object
      description: Wan2.6 image generation response.
      example:
        output:
          choices:
            - finish_reason: stop
              message:
                content:
                  - image: https://dashscope-result-intl.oss-cn-singapore.aliyuncs.com/xxx.png?Expires=xxx
                    type: image
                role: assistant
          finished: true
        usage:
          image_count: 1
          input_tokens: 0
          output_tokens: 0
          size: 1376*768
          total_tokens: 0
        request_id: a3f4befe-cacd-49c9-8298-xxxxxx
      properties:
        output:
          type: object
          properties:
            choices:
              type: array
              description: List of generated results.
              items:
                $ref: "#/components/schemas/Wan26ImageChoice"
            finished:
              type: boolean
              description: Whether the generation has completed.
        usage:
          type: object
          description: 'Usage statistics. Returned in the top-level `usage` field, at the same level as `output`. Read them as `response.usage["image_count"]`. The `output` object does not carry statistics: `response.output.usage` is returned as `{}` and contains no `image_count`.'
          properties:
            image_count:
              type: integer
              description: Number of images generated.
            input_tokens:
              type: integer
              description: Number of input tokens consumed.
            output_tokens:
              type: integer
              description: Number of output tokens consumed.
            size:
              type: string
              description: Resolution of the generated image(s).
            total_tokens:
              type: integer
              description: Total tokens consumed (input + output).
        request_id:
          type: string
          description: Unique request identifier for tracing and troubleshooting.
          example: a3f4befe-cacd-49c9-8298-xxxxxx
    Wan26ImageChoice:
      type: object
      properties:
        finish_reason:
          type: string
          description: "`stop` means normal completion. `null` indicates streaming is still in progress."
          example: stop
        message:
          type: object
          properties:
            role:
              type: string
              description: Always `assistant`.
              enum:
                - assistant
            content:
              type: array
              description: Response content array containing generated image URLs and/or text (in interleaved mode).
              items:
                $ref: "#/components/schemas/Wan26ImageResponseContentPart"
    Wan26ImageResponseContentPart:
      type: object
      description: Content part in the response. Can be an image or text.
      properties:
        type:
          type: string
          description: "Content type: `image` or `text`."
          enum:
            - image
            - text
        image:
          type: string
          description: URL of the generated image (PNG). **Valid for 24 hours.** Download promptly.
        text:
          type: string
          description: Text content (only present in interleaved text-image output mode).
    Wan26ImageAsyncRequest:
      type: object
      description: Request body for async Wan2.6 image generation/editing task.
      required:
        - model
        - input
      properties:
        model:
          type: string
          description: Model name. Set to `wan2.6-image`.
          enum:
            - wan2.6-image
          example: wan2.6-image
        input:
          type: object
          required:
            - messages
          description: Input data containing the messages array.
          properties:
            messages:
              type: array
              description: "Array of request content. Only single-turn conversations are supported. Provide one message with `role: user`."
              minItems: 1
              maxItems: 1
              items:
                $ref: "#/components/schemas/Wan26ImageMessage"
        parameters:
          $ref: "#/components/schemas/Wan26ImageParameters"
    AsyncTaskSubmitResponse:
      type: object
      description: Response returned when an asynchronous task is created successfully.
      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 for troubleshooting.
        output:
          type: object
          properties:
            task_id:
              type: string
              description: The task identifier. Use this to query the task status via `GET /tasks/{task_id}`. Valid for 24 hours.
            task_status:
              type: string
              description: The initial task status. Typically `PENDING`.
              enum:
                - PENDING
    Wan26TaskStatusResponse:
      type: object
      description: Response returned when querying async task status.
      properties:
        request_id:
          type: string
          description: Unique request identifier for troubleshooting.
        output:
          type: object
          description: Task output information.
          properties:
            task_id:
              type: string
              description: The task identifier.
            task_status:
              type: string
              description: The current task status.
              enum:
                - PENDING
                - RUNNING
                - SUCCEEDED
                - FAILED
                - CANCELED
                - UNKNOWN
            submit_time:
              type: string
              description: "Task submission time. Time is in UTC+8. Format: `YYYY-MM-DD HH:mm:ss.SSS`."
            scheduled_time:
              type: string
              description: "Time when the task started running. Format: `YYYY-MM-DD HH:mm:ss.SSS`."
            end_time:
              type: string
              description: "Time when the task completed. Format: `YYYY-MM-DD HH:mm:ss.SSS`."
            finished:
              type: boolean
              description: Whether the task has completed.
            choices:
              type: array
              description: List of generated results. Returned when `task_status` is `SUCCEEDED`.
              items:
                $ref: "#/components/schemas/Wan26ImageChoice"
        usage:
          type: object
          description: 'Usage statistics. Counts only successful results. Returned in the top-level `usage` field, at the same level as `output`. Read them as `response.usage["image_count"]`, where `image_count` is the total number of images generated by the task. The `output` object does not carry statistics: `response.output.usage` is returned as `{}` and contains no `image_count`.'
          properties:
            image_count:
              type: integer
              description: Number of images generated.
            input_tokens:
              type: integer
              description: Number of input tokens consumed.
            output_tokens:
              type: integer
              description: Number of output tokens consumed.
            size:
              type: string
              description: Resolution of the generated image(s).
            total_tokens:
              type: integer
              description: Total tokens consumed (input + output).
        code:
          type: string
          description: Error code. Returned only when the request fails.
        message:
          type: string
          description: Detailed error message. Returned only when the request fails.
    DashScopeErrorResponse:
      type: object
      description: DashScope API error response.
      example:
        request_id: a4d78a5f-655f-9639-8437-xxxxxx
        code: InvalidParameter
        message: num_images_per_prompt must be 1
      properties:
        request_id:
          type: string
          description: Unique request identifier.
        code:
          type: string
          description: Error code (e.g., `InvalidParameter`, `Throttling`, `InvalidApiKey`).
          example: InvalidParameter
        message:
          type: string
          description: Human-readable error message.
          example: num_images_per_prompt must be 1