> ## Documentation Index
> Fetch the complete documentation index at: https://docs.modelstudio.console.alibabacloud.com/llms.txt
> Use this file to discover all available pages before exploring further.

# Wan2.6 - image generation and editing

> Wan2.6 supports multi-image input, image editing, and interleaved text-image output.

## Model overview <span id="4a3e46b825d2k" /> <span id="b025183ba3ldr" />

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}><colgroup><col style={{ width: "18.07%" }} /><col style={{ width: "37.46%" }} /><col style={{ width: "44.47%" }} /></colgroup><thead><tr><th><p><strong>Model</strong></p></th><th><p><strong>Description</strong></p></th><th><p><strong>Output image specifications</strong></p></th></tr></thead><tbody><tr><td><p>wan2.6-image</p></td><td><p>Edits images and generates interleaved text-image output.</p></td><td><p>Image format: PNG</p> <p>Image resolution and dimensions are configured through the <a href="/en/model-studio/wan-image-generation-api-reference">size parameter</a>.</p></td></tr></tbody></table>

<Note>
  Before calling the API, check the [model list and pricing](/en/model-studio/model-pricing) supported in each region.
</Note>

## Prerequisites <span id="0e41425c577u4" /> <span id="e9c6aaa30fykr" />

[Obtain an API key](/en/model-studio/get-api-key) and [export the API key as an environment variable](/en/model-studio/get-api-key).

<Tip>
  The Singapore, US (Virginia), and China (Beijing) regions have separate <strong>API keys</strong> and <strong>request endpoints</strong>. They cannot be used interchangeably. Cross-region calls lead to authentication failures or service errors. For more information, see [Select a region and service deployment scope](/en/model-studio/regions).
</Tip>

## HTTP synchronous <span id="dac5ce452cwz1" /> <span id="8921959815l5m" />

Returns results in a single request. Recommended for most scenarios.

<Tabs>
  <Tab title="Singapore">
    `POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="US (Virginia)">
    `POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation`
  </Tab>

  <Tab title="China (Beijing)">
    `POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>
</Tabs>

> The global deployment scope (Frankfurt region) only supports [asynchronous calls](/en/model-studio/wan-image-generation-api-reference#42703589880ts).

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.92%" }} />

    <col style={{ width: "46.08%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Request parameters <span id="78f3155ff3r2l" /> <span id="1b3afeeb39rz8" />
      </td>

      <td rowSpan={9}>
        <Tabs>
          <Tab title="Image editing">
            ```bash expandable
            curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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"
                    }
                }'
            ```
          </Tab>

          <Tab title="Interleaved text-image output (streaming only)">
            When using interleaved text-image output (`parameters.enable_interleave = true`) with the synchronous interface, streaming is required. Set both conditions:

            - Set `X-DashScope-SSE` to `enable`.
            - Set `parameters.stream` to `true`.

            ```bash
            curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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
                    }
                }'
            ```
          </Tab>

          <Tab title="dashscope CLI">
            Call via the dashscope command line.

            ```bash
            export DASHSCOPE_API_KEY="your-api-key"
            # Replace {WorkspaceId} with your workspace ID, ap-southeast-1 with your region (e.g., us-east-1, eu-central-1)
            export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"
            dashscope image-generation create -m wan2.6-t2i -t "a cute cat"
            ```

            <Tip>The SDK Expert interactive assistant can accomplish the same development and troubleshooting via natural language, see [DashScope SDK Expert](/en/model-studio/dashscope-sdk-expert).</Tip>

            For the complete region table, see [Base URL overview](/en/model-studio/base-url).
          </Tab>
        </Tabs>
      </td>
    </tr>

    <tr>
      <td>
        ##### Request headers <span id="fd84180b66rpo" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>Content-Type</strong> `string` <strong>(Required)</strong>

        The content type of the request. Must be `application/json`.
      </td>
    </tr>

    <tr>
      <td>
        <strong>Authorization</strong> `string` <strong>(Required)</strong>

        Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
      </td>
    </tr>

    <tr>
      <td>
        <strong>X-DashScope-SSE</strong>`string` (Optional)

        Enables streaming output.

        - When `parameters.enable_interleave=true`, set to `enable`.
        - In other cases, omit this header.
      </td>
    </tr>

    <tr>
      <td>
        ##### Request body <span id="7d7bb26156npj" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>model</strong> `string` <strong>(Required)</strong>

        Model name. Set to wan2.6-image.
      </td>
    </tr>

    <tr>
      <td>
        <strong>input</strong> `object` <strong>(Required)</strong>

        Input configuration.

        <Accordion title="Properties" defaultOpen>
          <strong>messages</strong> `array` <strong>(Required)</strong>

          Request content array. <strong>Only single-turn conversations are supported</strong> -- provide one role-content pair.

          <Accordion title="Properties" defaultOpen>
            <strong>role</strong>`string` <strong>(Required)</strong>

            Message role. Set to `user`.

            <strong>content</strong>`array` <strong>(Required)</strong>

            Array of message content.

            <Accordion title="Properties" defaultOpen>
              <strong>text</strong>`string`<strong>(Required)</strong>

              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). Auto-truncated if exceeded.

              Example: Generate a tomato and egg stir-fry based on this image style.

              <strong>Note</strong>: The `content` array must contain exactly one object with a `text` field.

              <strong>image</strong>`string`(Optional)

              URL or Base64-encoded string of the input image.

              Image constraints:

              - Image formats: JPEG, JPG, PNG (alpha channel not supported), BMP, WebP.
              - Image resolution: Width and height must each be between 240 and 8,000 pixels.
              - File size: Must not exceed 10 MB.

              Image quantity limits:

              - The number of input images depends on the `parameters.enable_interleave` parameter.

                - When `enable_interleave=true` (interleaved text-image output), you can input <strong>0 to 1</strong> images.
                - When `enable_interleave=false` (image editing), you <strong>must</strong> input <strong>1 to 4</strong> images.
              - When you input multiple images, include multiple `image` objects in the `content` array, defining the image order by array sequence.

              Supported input formats:

              1. Use a publicly accessible URL

                 - Supports HTTP or HTTPS protocols.
                 - Example: `http://wanx.alicdn.com/material/xxx.jpeg`.
              2. Provide a Base64-encoded image string

                 - Format: data:\{MIME\_type};base64,\{base64\_data}
                 - Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (for illustration only; provide the complete string in practice)
                 - For Base64 encoding guidelines, see [Image input methods](/en/model-studio/wan-image-edit#8db0e2215frua).
            </Accordion>
          </Accordion>
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>parameters</strong> `object` (Optional)

        Generation parameters.

        <Accordion title="Properties" defaultOpen>
          <strong>negative\_prompt</strong> `string` (optional)

          A negative prompt describing what you do not want in the image.

          Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

          Example: Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth surfaces, AI-generated look. Chaotic composition. Blurry or distorted text.

          <strong>size</strong> `string` (Optional)

          Output image resolution. Supports two methods: referencing input image proportions or directly specifying dimensions.

          When `enable_interleave=false` (image editing mode):

          - Method 1: Reference input image proportions (recommended)

            Available output resolution options: `1K` (default), `2K`.

            - `1K`: Output total pixels close to 1280\*1280, maintaining the aspect ratio of the last input image.
            - `2K`: Output total pixels close to 2048\*2048, maintaining the aspect ratio of the last input image.
          - Method 2: Specify output image width and height in pixels

            Total pixels must be between \[768*768, 2048*2048], with an aspect ratio range of \[1:4, 4:1].

            > Actual output pixel values are multiples of 16 closest to the specified value.

          When `enable_interleave=true` (interleaved text-image output mode):

          - Method 1: Reference input image proportions (default method)

            - If total input image pixels ≤ 1280\*1280, output matches the input's total pixels and aspect ratio.
            - If total input image pixels > 1280*1280, output total pixels are close to 1280*1280, maintaining the input's aspect ratio.
            - If no input image is provided, the output size is 1280\*1280.
          - Method 2: Specify output image width and height in pixels

            Total pixels must be between \[768*768, 1280*1280], with an aspect ratio range of \[1:4, 4:1].

            > Actual output pixel values are multiples of 16 closest to the specified value.

          <Accordion title="Recommended resolutions for common aspect ratios" defaultOpen>
            * 1:1: 1280\*1280
            * 2:3: 800\*1200
            * 3:2: 1200\*800
            * 3:4: 960\*1280
            * 4:3: 1280\*960
            * 9:16: 720\*1280
            * 16:9: 1280\*720
            * 21:9: 1344\*576
          </Accordion>

          <strong>enable\_interleave</strong> `bool` (Optional)

          Controls image generation mode:

          - false (default): Indicates image editing mode (supports multi-image input and subject consistency generation).

            - Use case: Edit, apply style transfer, or generate subject-consistent images based on 1 to 4 input images.
            - Input: Must provide at least one reference image.
            - Output: Can generate 1 to 4 result images.
          - true: Enables interleaved text-image output mode (supports inputting one image or no image).

            - Use case: Generate content combining text and images based on a text description, or perform pure text-to-image generation.
            - Input: Can provide no image (text-to-image) or up to one reference image.
            - Output: Generates mixed content containing both text and images.

          <strong>n</strong> `integer` (Optional)

          <Tip>
            This parameter affects cost (charged per successful image -- see [pricing](/en/model-studio/model-pricing)).
          </Tip>

          Number of images to generate. Behavior depends on `enable_interleave`:

          - When `enable_interleave=false` (image editing mode):

            - Directly controls the number of generated images.
            - Range: 1 to 4. Default value is 4.
            - During testing, set this value to 1 for low-cost validation.
          - When `enable_interleave=true` (interleaved text-image mode):

            - Defaults to 1 and must remain 1. Any other value causes an error.
            - Use `max_images` to control the image count in this mode.

          <strong>max\_images</strong> `integer` (Optional)

          <Tip>
            This parameter affects cost (charged per successful image -- see [pricing](/en/model-studio/model-pricing)).
          </Tip>

          Only effective in interleaved text-image mode (`enable_interleave=true`).

          - Maximum number of images the model generates in a single response.
          - Range: 1 to 5. Default value is 5.
          - Sets the upper bound. The model may generate fewer images than requested.

          <strong>prompt\_extend</strong> `bool` (Optional)

          Only effective in image editing mode (`enable_interleave = false`).

          Enables intelligent prompt rewriting. Optimizes positive prompt only; negative prompt remains unchanged.

          - true (default)
          - false

          <strong>stream</strong> `bool` (Optional)

          Enables streaming output. <strong>Required</strong> (set to `true`) when `enable_interleave=true`.

          - false (default)
          - true

          <strong>watermark</strong> `bool` (Optional)

          Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated".

          - false (default)
          - true

          <strong>seed</strong> `integer` (optional)

          Random number seed. Valid range: `[0,2147483647]`.

          Using the same `seed` yields similar outputs. If omitted, the algorithm uses a random seed.

          <strong>Note:</strong> Image generation is probabilistic. Even with the same `seed`, results may vary.
        </Accordion>
      </td>
    </tr>
  </tbody>
</table>

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.61%" }} />

    <col style={{ width: "46.39%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Response parameters <span id="dee809656c79t" /> <span id="85403473eac16" />
      </td>

      <td rowSpan={4}>
        <Tabs>
          <Tab title="Successful task execution">
            Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

            ```json expandable
            {
                "output": {
                    "choices": [
                        {
                            "finish_reason": "stop",
                            "message": {
                                "content": [
                                    {
                                        "image": "https://dashscope-result-bj.oss-cn-beijing.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"
            }
            ```
          </Tab>

          <Tab title="Successful task execution (streaming output)">
            Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

            ```json
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"meat"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":571,"image_count":3,"output_tokens":543,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"fragrant"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":572,"image_count":3,"output_tokens":544,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"intertwine"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":573,"image_count":3,"output_tokens":545,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            ......
            {"output":{"choices":[{"message":{"content":[{"type":"image","image":"https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.png?Expires=xxxx"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":557,"image_count":3,"output_tokens":529,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"while"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":558,"image_count":3,"output_tokens":530,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"hot"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":559,"image_count":3,"output_tokens":531,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"pinch"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":560,"image_count":3,"output_tokens":532,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"up"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":561,"image_count":3,"output_tokens":533,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"a piece of"}],"role":"assistant"},"finish_reason":"null"}],"finished":true},"usage":{"total_tokens":562,"image_count":3,"output_tokens":534,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            {"output":{"choices":[{"message":{"content":[{"type":"text","text":"meat"}],"role":"assistant"},"finish_reason":"stop"}],"finished":true},"usage":{"total_tokens":563,"image_count":3,"output_tokens":535,"size":"1280*1280","input_tokens":28},"request_id":"d2dcb952-bf91-4a6a-aad5-xxxxxx"}
            ```
          </Tab>

          <Tab title="Task execution failure">
            If the task fails, error information is returned. Use the code and message fields to identify the cause. See [Error codes](/en/model-studio/error-code) for troubleshooting.

            ```json
            {
                "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
                "code": "InvalidParameter",
                "message": "num_images_per_prompt must be 1"
            }
            ```
          </Tab>
        </Tabs>
      </td>
    </tr>

    <tr>
      <td>
        <strong>output</strong> `object`

        Task output.

        <Accordion title="Properties" defaultOpen>
          <strong>choices</strong> `array of object`

          Model-generated output content.

          <Accordion title="Properties" defaultOpen>
            <strong>finish\_reason</strong> `string`

            Reason for task termination.

            <strong>Non-streaming output scenario</strong>: Naturally stops with `stop`.

            <strong>Streaming output scenario</strong>: This parameter indicates whether the data stream has finished transmitting.

            - During transmission: Previous data packets continuously return `"finish_reason": "null"`, indicating content is still being generated. Continue receiving.
            - At transmission end: Only the <strong>last</strong> JSON structure returns `"finish_reason":"stop"`, indicating the streaming request has fully completed. Stop receiving.

            <strong>message</strong> `object`

            Message returned by the model.

            <Accordion title="Properties" defaultOpen>
              <strong>role</strong>`string`

              Message role, fixed as `assistant`.

              <strong>content</strong>`array`

              <Accordion title="Properties" defaultOpen>
                <strong>type</strong> `string`

                Output type. Enumerated values: text, image.

                <strong>text</strong> `string`

                Generated text.

                <strong>image</strong> `string`

                URL of the generated image in PNG format.

                <strong>Link expires after 24 hours</strong>. Download and save the image promptly.
              </Accordion>
            </Accordion>
          </Accordion>

          <strong>finished</strong> `bool`

          Request completion flag.

          - true
          - false
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>usage</strong> `object`

        Output statistics. Only counts successful results.

        <Accordion title="Properties" defaultOpen>
          <strong>image\_count</strong> `integer`

          Number of generated images.

          <strong>size</strong> `string`

          Resolution of generated images. Example: 1376\*768.

          <strong>input\_tokens</strong> `integer`

          Billed per image count.

          - In image editing mode, fixed at 0.
          - In interleaved text-image mode, this field counts input text tokens (not billed).

          <strong>output\_tokens</strong> `integer`

          Billed per image count.

          - In image editing mode, fixed at 0.
          - In interleaved text-image mode, this field counts output text tokens (not billed).

          <strong>total\_tokens</strong>`integer`

          Billed per image count.

          - In image editing mode, fixed at 0.
          - In interleaved text-image mode, this field counts total tokens (not billed).
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>request\_id</strong> `string`

        Unique request identifier for tracing and troubleshooting.
      </td>
    </tr>

    <tr>
      <td>
        <strong>code</strong> `string`

        Error code. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>

      <td />
    </tr>

    <tr>
      <td>
        <strong>message</strong> `string`

        Detailed error message. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>

      <td />
    </tr>
  </tbody>
</table>

## HTTP asynchronous <span id="42703589880ts" /> <span id="7c782df20fkq8" />

Process: <strong>Create task → Poll results</strong>

### Step 1: Create task and get task ID <span id="db8cf70432oe3" /> <span id="1a5d85859608j" />

<Tabs>
  <Tab title="Singapore">
    `POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="US (Virginia)">
    `POST https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation`
  </Tab>

  <Tab title="China (Beijing)">
    `POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="Germany (Frankfurt)">
    `POST https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1/services/aigc/image-generation/generation`

    When you make a call, replace `{WorkspaceId}` with your [Workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>
</Tabs>

<Note>
  - After the task is created, use the returned `task_id` to query the result. The `task_id` is valid for 24 hours. <strong>Do not create duplicate tasks</strong>. Instead, use polling to retrieve the result.
  - For guidance for beginners, see [Call APIs with Postman or cURL](/en/model-studio/first-call-to-image-and-video-api).
</Note>

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.92%" }} />

    <col style={{ width: "46.08%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Request parameters <span id="f54fd191909ri" /> <span id="01607c9829c8r" />
      </td>

      <td rowSpan={9}>
        <CodeGroup>
          ```bash Image editing expandable
          curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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": "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"
                  }
              }'
          ```

          ```bash Interleaved text-image output
          curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.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": "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",
                      "enable_interleave":true
                  }
              }'
          ```
        </CodeGroup>
      </td>
    </tr>

    <tr>
      <td>
        ##### Request headers <span id="0d489ca36e4mj" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>Content-Type</strong> `string` <strong>(Required)</strong>

        The content type of the request. Must be `application/json`.
      </td>
    </tr>

    <tr>
      <td>
        <strong>Authorization</strong> `string` <strong>(Required)</strong>

        Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
      </td>
    </tr>

    <tr>
      <td>
        <strong>X-DashScope-Async</strong>`string`<strong>(Required)</strong>

        Asynchronous mode switch. <strong>Must be set to</strong> `enable`.

        <Tip>
          Omitting this header returns the error: “current user api does not support synchronous calls”.
        </Tip>
      </td>
    </tr>

    <tr>
      <td>
        ##### Request body <span id="d6b6a20821cp8" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>model</strong> `string` <strong>(Required)</strong>

        Model name.

        Example: wan2.6-image
      </td>
    </tr>

    <tr>
      <td>
        <strong>input</strong> `object` <strong>(Required)</strong>

        Input configuration.

        <Accordion title="Properties" defaultOpen>
          <strong>messages</strong> `array` <strong>(Required)</strong>

          Request content array. <strong>Only single-turn conversations are supported</strong> — provide one role-content pair. Multi-turn conversations are not supported.

          <Accordion title="Properties" defaultOpen>
            <strong>role</strong>`string` <strong>(Required)</strong>

            Message role. Set to `user`.

            <strong>content</strong>`array` <strong>(Required)</strong>

            Array of message content.

            <Accordion title="Properties" defaultOpen>
              <strong>text</strong>`string`<strong>(Required)</strong>

              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). Auto-truncated if exceeded.

              Example: Generate a tomato and egg stir-fry based on this image style.

              <strong>Note</strong>: The `content` array must contain exactly one object with a `text` field.

              <strong>image</strong>`string`(Optional)

              URL or Base64-encoded string of the input image.

              Image constraints:

              - Image formats: JPEG, JPG, PNG (alpha channel not supported), BMP, WebP.
              - Image resolution: Width and height must each be between 240 and 8,000 pixels.
              - File size: Must not exceed 10 MB.

              Image quantity limits:

              - The number of input images depends on the `parameters.enable_interleave` parameter.

                - When `enable_interleave=true` (interleaved text-image output), you can input <strong>0 to 1</strong> images.
                - When `enable_interleave=false` (image editing), you <strong>must</strong> input <strong>1 to 4</strong> images.
              - When you input multiple images, include multiple `image` objects in the `content` array, defining the image order by array sequence.

              Supported input formats:

              1. Use a publicly accessible URL

                 - Supports HTTP or HTTPS protocols.
                 - Example: `http://wanx.alicdn.com/material/xxx.jpeg`.
              2. Provide a Base64-encoded image string

                 - Format: data:\{MIME\_type};base64,\{base64\_data}
                 - Example: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (for illustration only; provide the complete string in practice)
                 - For Base64 encoding guidelines, see [Image input methods](/en/model-studio/wan-image-edit#8db0e2215frua).
            </Accordion>
          </Accordion>
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>parameters</strong> `object` (Optional)

        Generation parameters.

        <Accordion title="Properties" defaultOpen>
          <strong>negative\_prompt</strong> `string` (optional)

          A negative prompt describing what you do not want in the image.

          Supports Chinese and English. Maximum length is 500 characters. Excess characters are truncated automatically.

          Example: Low resolution, low quality, distorted limbs, malformed fingers, oversaturated colors, wax-like appearance, no facial details, overly smooth surfaces, AI-generated look. Chaotic composition. Blurry or distorted text.

          <strong>size</strong> `string` (Optional)

          Output image resolution. Supports two methods: referencing input image proportions or directly specifying dimensions.

          When `enable_interleave=false` (image editing mode):

          - Method 1: Reference input image proportions (recommended)

            Available output resolution options: `1K` (default), `2K`.

            - `1K`: Output total pixels close to 1280\*1280, maintaining the aspect ratio of the last input image.
            - `2K`: Output total pixels close to 2048\*2048, maintaining the aspect ratio of the last input image.
          - Method 2: Specify output image width and height in pixels

            Total pixels must be between \[768*768, 2048*2048], with an aspect ratio range of \[1:4, 4:1].

            > Actual output pixel values are multiples of 16 closest to the specified value.

          When `enable_interleave=true` (interleaved text-image output mode):

          - Method 1: Reference input image proportions (default method)

            - If total input image pixels ≤ 1280\*1280, output matches the input's total pixels and aspect ratio.
            - If total input image pixels > 1280*1280, output total pixels are close to 1280*1280, maintaining the input's aspect ratio.
            - If no input image is provided, the output size is 1280\*1280.
          - Method 2: Specify output image width and height in pixels

            Total pixels must be between \[768*768, 1280*1280], with an aspect ratio range of \[1:4, 4:1].

            > Actual output pixel values are multiples of 16 closest to the specified value.

          <Accordion title="Recommended resolutions for common aspect ratios" defaultOpen>
            * 1:1: 1280\*1280
            * 2:3: 800\*1200
            * 3:2: 1200\*800
            * 3:4: 960\*1280
            * 4:3: 1280\*960
            * 9:16: 720\*1280
            * 16:9: 1280\*720
            * 21:9: 1344\*576
          </Accordion>

          <strong>enable\_interleave</strong> `bool` (Optional)

          Controls image generation mode:

          - false (default): Indicates image editing mode (supports multi-image input and subject consistency generation).

            - Use case: Edit, apply style transfer, or generate subject-consistent images based on 1 to 4 input images.
            - Input: Must provide at least one reference image.
            - Output: Can generate 1 to 4 result images.
          - true: Enables interleaved text-image output mode (supports inputting one image or no image).

            - Use case: Generate content combining text and images based on a text description, or perform pure text-to-image generation.
            - Input: Can provide no image (text-to-image) or up to one reference image.
            - Output: Generates mixed content containing both text and images.

          <strong>n</strong> `integer` (Optional)

          <Tip>
            This parameter affects cost (charged per successful image -- see [pricing](/en/model-studio/model-pricing)).
          </Tip>

          Number of images to generate. Behavior depends on `enable_interleave`:

          - When `enable_interleave=false` (image editing mode):

            - Directly controls the number of generated images.
            - Range: 1 to 4. Default value is 4.
            - During testing, set this value to 1 for low-cost validation.
          - When `enable_interleave=true` (interleaved text-image mode):

            - Defaults to 1 and must remain 1. Any other value causes an error.
            - Use `max_images` to control the image count in this mode.

          <strong>max\_images</strong> `integer` (Optional)

          <Tip>
            This parameter affects cost (charged per successful image -- see [pricing](/en/model-studio/model-pricing)).
          </Tip>

          Only effective in interleaved text-image mode (`enable_interleave=true`).

          - Maximum number of images the model generates in a single response.
          - Range: 1 to 5. Default value is 5.
          - Sets the upper bound. The model may generate fewer images than requested.

          <strong>prompt\_extend</strong> `bool` (Optional)

          Only effective in image editing mode (`enable_interleave = false`).

          Enables intelligent prompt rewriting. Optimizes positive prompt only; negative prompt remains unchanged.

          - true (default)
          - false

          <strong>watermark</strong> `bool` (Optional)

          Adds a watermark label in the bottom-right corner of the image with fixed text "AI Generated".

          - false (default)
          - true

          <strong>seed</strong> `integer` (optional)

          Random number seed. Valid range: `[0,2147483647]`.

          Using the same `seed` yields similar outputs. If omitted, the algorithm uses a random seed.

          <strong>Note:</strong> Image generation is probabilistic. Even with the same `seed`, results may vary.
        </Accordion>
      </td>
    </tr>
  </tbody>
</table>

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.56%" }} />

    <col style={{ width: "46.44%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Response parameters <span id="cd3063363egdc" /> <span id="f5d1a44542v6q" />
      </td>

      <td rowSpan={3}>
        <Tabs>
          <Tab title="Successful response">
            Save the `task_id` to query the task status and result.

            ```json
            {
                "output": {
                    "task_status": "PENDING",
                    "task_id": "0385dc79-5ff8-4d82-bcb6-xxxxxx"
                },
                "request_id": "4909100c-7b5a-9f92-bfe5-xxxxxx"
            }
            ```
          </Tab>

          <Tab title="Error response">
            Task creation failed. See [Error codes](/en/model-studio/error-code).

            ```json
            {
                "code": "InvalidApiKey",
                "message": "Invalid API-key provided.",
                "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
            }
            ```
          </Tab>
        </Tabs>
      </td>
    </tr>

    <tr>
      <td>
        <strong>output</strong> `object`

        Task output.

        <Accordion title="Properties" defaultOpen>
          <strong>task\_id</strong> `string`

          The task ID. Valid for queries for 24 hours.

          <strong>task\_status</strong> `string`

          The status of the task.

          <Accordion title="Enumeration values" defaultOpen>
            - PENDING
            - RUNNING
            - SUCCEEDED
            - FAILED
            - CANCELED
            - UNKNOWN: The task does not exist or its status is unknown.
          </Accordion>
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>request\_id</strong> `string`

        Unique request identifier for tracing and troubleshooting.
      </td>
    </tr>

    <tr>
      <td>
        <strong>code</strong> `string`

        Error code. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>

      <td />
    </tr>

    <tr>
      <td>
        <strong>message</strong> `string`

        Detailed error message. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>

      <td />
    </tr>
  </tbody>
</table>

### Step 2: Query results using task ID <span id="420e6e77a17om" /> <span id="522f623f9ex6a" />

<Tabs>
  <Tab title="Singapore">
    `GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="US (Virginia)">
    `GET https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/tasks/{task_id}`
  </Tab>

  <Tab title="China (Beijing)">
    `GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="Germany (Frankfurt)">
    `GET https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tasks/{task_id}`

    When you make a call, replace `{WorkspaceId}` with your actual [Workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>
</Tabs>

<Note>
  - <strong>Polling recommendation</strong>: Image generation is time-consuming. Use a polling mechanism with a reasonable interval, such as 10 seconds.
  - <strong>Task state transition</strong>: PENDING → RUNNING → SUCCEEDED or FAILED.
  - <strong>Result link</strong>: After a task succeeds, an image URL valid for <strong>24 hours</strong> is returned. Download and save the image to permanent storage, such as [OSS](https://www.alibabacloud.com/help/en/doc-detail/31817.htm).
</Note>

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.75%" }} />

    <col style={{ width: "46.25%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Request parameters <span id="eb9c8d77b6xg8" /> <span id="8c886cd95fbnn" />
      </td>

      <td rowSpan={5}>
        <Tabs>
          <Tab title="Query task results">
            Replace `{task_id}` with the `task_id` value returned by the previous API call. The `task_id` is valid for queries for 24 hours, Replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).

            ```bash
            curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
            --header "Authorization: Bearer $DASHSCOPE_API_KEY"
            ```
          </Tab>
        </Tabs>
      </td>
    </tr>

    <tr>
      <td>
        ##### Request headers <span id="36a28b657f196" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>Authorization</strong> `string` <strong>(Required)</strong>

        Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.
      </td>
    </tr>

    <tr>
      <td>
        ##### URL path parameters <span id="0e29e015d8opn" />
      </td>
    </tr>

    <tr>
      <td>
        <strong>task\_id</strong> `string` <strong>(Required)</strong>

        The ID of the task.
      </td>
    </tr>
  </tbody>
</table>

<table style={{ display: "table", tableLayout: "fixed", width: "100%" }}>
  <colgroup>
    <col style={{ width: "53.6%" }} />

    <col style={{ width: "46.4%" }} />
  </colgroup>

  <tbody>
    <tr>
      <td>
        #### Response parameters <span id="b7e833ee1f962" /> <span id="9da14e4708vp6" />
      </td>

      <td rowSpan={6}>
        <Tabs>
          <Tab title="Successful task execution">
            Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

            ```json expandable
            {
                "request_id": "43d9e959-25bc-4dc7-9888-xxxxxx",
                "output": {
                    "task_id": "858cad55-4bdc-4ba3-ae6c-xxxxxx",
                    "task_status": "SUCCEEDED",
                    "submit_time": "2025-12-16 04:21:02.275",
                    "scheduled_time": "2025-12-16 04:21:02.304",
                    "end_time": "2025-12-16 04:24:46.658",
                    "finished": true,
                    "choices": [
                        {
                            "finish_reason": "stop",
                            "message": {
                                "role": "assistant",
                                "content": [
                                    {
                                        "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/1xxx.png?Expires=xxx",
                                        "type": "image"
                                    }
                                ]
                            }
                        },
                        {
                            "finish_reason": "stop",
                            "message": {
                                "role": "assistant",
                                "content": [
                                    {
                                        "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/1xxx.png?Expires=xxx",
                                        "type": "image"
                                    }
                                ]
                            }
                        }
                    ]
                },
                "usage": {
                    "size": "1376*768",
                    "total_tokens": 0,
                    "image_count": 2,
                    "output_tokens": 0,
                    "input_tokens": 0
                }
            }
            ```
          </Tab>

          <Tab title="Task execution failure">
            If the task fails, error information is returned. Use the code and message fields to identify the cause. See [Error codes](/en/model-studio/error-code) for troubleshooting.

            ```json
            {
                "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
                "code": "InvalidParameter",
                "message": "num_images_per_prompt must be 1"
            }
            ```
          </Tab>
        </Tabs>
      </td>
    </tr>

    <tr>
      <td>
        <strong>output</strong> `object`

        Task output information.

        <Accordion title="Properties" defaultOpen>
          <strong>task\_id</strong> `string`

          The task ID. Valid for queries for 24 hours.

          <strong>task\_status</strong> `string`

          The status of the task.

          <Accordion title="Enumeration values" defaultOpen>
            - PENDING
            - RUNNING
            - SUCCEEDED
            - FAILED
            - CANCELED
            - UNKNOWN: The task does not exist or its status is unknown.
          </Accordion>

          <strong>State transitions during polling:</strong>

          - PENDING → RUNNING → SUCCEEDED or FAILED.
          - The initial query status is usually PENDING or RUNNING.
          - When the status changes to SUCCEEDED, the response contains the generated image URL.
          - If the status is FAILED, check the error message and retry the task.

          <strong>submit\_time</strong> `string`

          The time when the task was submitted. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

          <strong>scheduled\_time</strong> `string`

          The time when the task was executed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

          <strong>end\_time</strong> `string`

          The time when the task was completed. The time is in UTC+8 and the format is YYYY-MM-DD HH:mm:ss.SSS.

          <strong>finished</strong> `bool`

          Request completion flag.

          - true
          - false

          <strong>choices</strong> `array of object`

          Model-generated output content.

          <Accordion title="Properties" defaultOpen>
            <strong>finish\_reason</strong> `string`

            Reason for task termination. Naturally stops with `stop`.

            <strong>message</strong> `object`

            Message returned by the model.

            <Accordion title="Properties" defaultOpen>
              <strong>role</strong>`string`

              Message role, fixed as `assistant`.

              <strong>content</strong>`array`

              <Accordion title="Properties" defaultOpen>
                <strong>type</strong> `string`

                Output type. Enumerated values: text, image.

                <strong>text</strong> `string`

                Generated text.

                <strong>image</strong> `string`

                URL of the generated image in PNG format.

                <strong>Link expires after 24 hours</strong>. Download and save the image promptly.
              </Accordion>
            </Accordion>
          </Accordion>
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>usage</strong> `object`

        Output statistics. Counts only successful results.

        <Accordion title="Properties" defaultOpen>
          <strong>image\_count</strong> `integer`

          Number of generated images.

          <strong>size</strong> `string`

          Resolution of generated images. Example: 1376\*768.

          <strong>input\_tokens</strong> `integer`

          Input token count. Billed per image count. Currently fixed at 0.

          <strong>output\_tokens</strong> `integer`

          Output token count. Billed per image count. Currently fixed at 0.

          <strong>total\_tokens</strong>`integer`

          Total token count. Billed per image count. Currently fixed at 0.
        </Accordion>
      </td>
    </tr>

    <tr>
      <td>
        <strong>request\_id</strong> `string`

        Unique request identifier for tracing and troubleshooting.
      </td>
    </tr>

    <tr>
      <td>
        <strong>code</strong> `string`

        Error code. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>
    </tr>

    <tr>
      <td>
        <strong>message</strong> `string`

        Detailed error message. Returned only for failed requests. See [Error codes](/en/model-studio/error-code).
      </td>
    </tr>
  </tbody>
</table>

## DashScope Python SDK <span id="1751252d8bf7c" /> <span id="c6869e22baz8w" />

SDK parameters align with the HTTP interface, adapted per language conventions.

The SDK handles asynchronous calls internally and supports both synchronous and asynchronous invocation.

> Actual duration varies by queue length and service load.

<Tip>
  Requires DashScope Python SDK <strong>version 1.25.8 or later</strong>. [Install SDK](/en/model-studio/install-sdk).
</Tip>

The `base_url` and API key are region-specific. Example call from the Singapore region:

<Tabs>
  <Tab title="Singapore">
    `https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="US (Virginia)">
    `https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1`
  </Tab>

  <Tab title="China (Beijing)">
    `https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="Germany (Frankfurt)">
    `https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1`

    Replace `{WorkspaceId}` with your actual [Workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>
</Tabs>

> The global deployment scope (Frankfurt region) only supports asynchronous calls.

### Image editing <span id="626b76fc868or" /> <span id="613054fc39tdl" />

<Tabs>
  <Tab title="Synchronous">
    ##### Request example <span id="1f90197d8cagy" /> <span id="4d0d9e4aef5cm" />

    ```python expandable
    import os
    import dashscope
    from dashscope.aigc.image_generation import ImageGeneration
    from dashscope.api_entities.dashscope_response import Message

    # Singapore region base_url. Base URLs differ by region.
    dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

    # If environment variable is not configured, replace the next line with: api_key="sk-xxx"
    # API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    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)
    ```

    ##### Response example <span id="b0515f126ag6l" /> <span id="1c1f91eeed3to" />

    > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "status_code": 200,
        "request_id": "b6a4c68d-3a91-4018-ae96-3cf373xxxxxx",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "audio": null,
            "finished": true
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0,
            "image_count": 1,
            "size": "1376*768",
            "total_tokens": 0
        }
    }
    ```

    Output statistics are 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`.
  </Tab>

  <Tab title="Asynchronous">
    ##### Request example <span id="7bd0a67abeuuz" /> <span id="d9c6b033cdcl4" />

    ```python expandable
    import os
    import dashscope
    from dashscope.aigc.image_generation import ImageGeneration
    from dashscope.api_entities.dashscope_response import Message
    from http import HTTPStatus

    # Singapore region base_url. Base URLs differ by region.
    dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

    # If environment variable is not configured, replace the next line with: api_key="sk-xxx"
    # API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key = os.getenv("DASHSCOPE_API_KEY")

    # Create asynchronous task
    def create_async_task():
        print("Creating async task...")
        message = Message(
            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'}
            ]
        )
        response = ImageGeneration.async_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"
        )

        if response.status_code == 200:
            print("Task created successfully:", response)
            return response  # Return task ID
        else:
            raise Exception(f"Failed to create task: {response.code} - {response.message}")

    # Wait for task completion
    def wait_for_completion(task_response):
        print("Waiting for task completion...")
        status = ImageGeneration.wait(task=task_response, api_key=api_key)

        if status.output.task_status == "SUCCEEDED":
            print("Task succeeded!")
            print("Response:", status)
        else:
            raise Exception(f"Task failed with status: {status.output.task_status}")

    # Fetch asynchronous task info
    def fetch_task_status(task):
        print("Fetching task status...")
        status = ImageGeneration.fetch(task=task, api_key=api_key)

        if status.status_code == HTTPStatus.OK:
            print("Task status:", status.output.task_status)
            print("Response details:", status)
        else:
            print(f"Failed to fetch status: {status.code} - {status.message}")

    # Cancel asynchronous task
    def cancel_task(task):
        print("Canceling task...")
        response = ImageGeneration.cancel(task=task, api_key=api_key)

        if response.status_code == HTTPStatus.OK:
            print("Task canceled successfully:", response.output.task_status)
        else:
            print(f"Failed to cancel task: {response.code} - {response.message}")

    # Main execution flow
    if __name__ == "__main__":
        task = create_async_task()
        wait_for_completion(task)
    ```

    ##### Response example <span id="d5de68e40618u" /> <span id="170d90d502iud" />

    1. Task creation response example

    ```json
    {
        "status_code": 200,
        "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": null,
            "audio": null,
            "task_id": "127ec645-118f-4884-955d-0eba8dxxxxxx",
            "task_status": "PENDING"
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0
        }
    }
    ```

    1. Task result query response example

       > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "status_code": 200,
        "request_id": "b2a7fab4-5e00-4b0a-86fe-8b9964xxxxxx",
        "code": null,
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "audio": null,
            "task_id": "127ec645-118f-4884-955d-0eba8xxxxxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2026-01-09 17:52:04.136",
            "scheduled_time": "2026-01-09 17:52:04.164",
            "end_time": "2026-01-09 17:52:25.408",
            "finished": true
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0,
            "size": "1376*768",
            "total_tokens": 0,
            "image_count": 1
        }
    }
    ```

    Output statistics are returned in the top-level `usage` field, at the same level as `output`. Read them as `response.usage["image_count"]`. The `output` object of an asynchronous task result does not carry statistics: `response.output.usage` is returned as `{}` and contains no `image_count`.
  </Tab>
</Tabs>

### Interleaved text-image output <span id="a988ae3cdau3e" /> <span id="f6b584bc68b0l" />

<Tabs>
  <Tab title="Synchronous (streaming only)">
    ##### Request example <span id="e677ebd437p7j" /> <span id="936e871941rri" />

    ```python expandable
    import os
    import dashscope
    from dashscope.aigc.image_generation import ImageGeneration
    from dashscope.api_entities.dashscope_response import Message

    # Singapore region URL. Base URLs differ by region.
    dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

    # If environment variable is not configured, replace the next line with: api_key="sk-xxx"
    # API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    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()
    ```

    ##### Response example <span id="95e7baa6180vj" /> <span id="88dced35180o4" />

    > URL expires after 24 hours. Download images promptly.

    ```json
    {"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Chili"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 0, "characters": 0, "total_tokens": 28, "image_count": 0, "size": "0*0"}}
    {"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Stir-fry"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 1, "characters": 0, "total_tokens": 29, "image_count": 0, "size": "0*0"}}
    {"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Pork"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 2, "characters": 0, "total_tokens": 30, "image_count": 0, "size": "0*0"}}

    ......

    {"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "."}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 398, "characters": 0, "total_tokens": 426, "image_count": 2, "size": "1280*1280"}}
    {"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": "stop", "choices": [{"finish_reason": "stop", "message": {"role": "assistant", "content": [{"type": "image", "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"}]}}], "audio": null, "finished": true}, "usage": {"input_tokens": 28, "output_tokens": 523, "characters": 0, "total_tokens": 551, "image_count": 3, "size": "1280*1280"}}
    ```
  </Tab>

  <Tab title="Asynchronous">
    ##### Request example <span id="ef2f7d167d3dx" /> <span id="821f410a47bsy" />

    <strong>Note</strong>: Asynchronous calls do not require the stream parameter

    ```python expandable
    import os
    import dashscope
    from dashscope.aigc.image_generation import ImageGeneration
    from dashscope.api_entities.dashscope_response import Message
    from http import HTTPStatus

    # Singapore region URL. Base URLs differ by region.
    dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

    # If environment variable is not configured, replace the next line with: api_key="sk-xxx"
    # API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
    api_key = os.getenv("DASHSCOPE_API_KEY")

    def main():
        """Asynchronous call - Text-image output"""
        print("========== wan2.6-image Asynchronous call - Text-image output ==========")

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

        # Create asynchronous task
        print("---async call, creating task----")
        response = ImageGeneration.async_call(
            model="wan2.6-image",
            api_key=api_key,
            messages=[image_message],
            # Asynchronous calls do not require stream parameter
            negative_prompt="",
            enable_interleave=True,
            max_images=3,
            size="1280*1280"
        )

        if response.status_code == HTTPStatus.OK:
            print(f"Task created successfully:")
            print(response)

            # Wait for task completion
            print("\n---waiting for task completion----")
            status = ImageGeneration.wait(task=response, api_key=api_key)

            if status.output.task_status == "SUCCEEDED":
                print("Task completed!")
                print(f"Results:")
                print(status)
            else:
                print(f"Task failed, status: {status.output.task_status}")
        else:
            print(f"Task creation failed: {response.code} - {response.message}")

    if __name__ == "__main__":
        try:
            main()
        except Exception as e:
            print(f"Execution error: {str(e)}")
            import traceback
            traceback.print_exc()
    ```

    ##### Response example <span id="3831331c686e8" /> <span id="47c67cfa6elog" />

    1. Task creation response example

    ```json
    {
        "status_code": 200,
        "request_id": "4fb3050f-de57-4a24-84ff-e37ee5xxxxxx",
        "code": "",
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": null,
            "audio": null,
            "task_id": "5c67585e-a3be-4943-b04d-c3fbb2xxxxxx",
            "task_status": "PENDING"
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "characters": 0
        }
    }
    ```

    1. Task result query response example

       > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "status_code": 200,
        "request_id": "997a759b-fbb9-4b35-9a4d-6dab1xxxxxx",
        "code": null,
        "message": "",
        "output": {
            "text": null,
            "finish_reason": null,
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "text": "Stir-fried pork with chili peppers is a classic Hunan dish and a beloved home-cooked favorite for many. Known for its fresh spiciness and tender meat, it's simple to prepare yet delivers an exceptional flavor experience. Today, we'll learn how to make this dish.\n\nFirst, preparing all ingredients is the key to success. Fresh pork, red and green chili peppers, garlic cloves, and ginger slices are essential. Slice the pork thinly, cut the chilies into segments, and mince the garlic and ginger.",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            },
                            {
                                "text": "Next comes the crucial stir-frying step. Heat oil in a wok over high heat. Add minced garlic and ginger to release their aroma, then add the sliced pork. Quickly stir-fry until the pork changes color. Once fragrant, add the chili segments and continue stir-frying to fully release the chili aroma, perfectly blending with the pork's tenderness.",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            },
                            {
                                "text": "Finally, season with light soy sauce, dark soy sauce, oyster sauce, and a pinch of sugar. Stir-fry quickly until evenly coated. Cook until the sauce thickens slightly, then turn off the heat and serve. Your delicious, aromatic stir-fried pork with chili peppers is ready!",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "audio": null,
            "task_id": "5c67585e-a3be-4943-b04d-c3fbb2xxxxxx",
            "task_status": "SUCCEEDED",
            "submit_time": "2026-01-16 17:47:39.469",
            "scheduled_time": "2026-01-16 17:47:39.804",
            "end_time": "2026-01-16 17:49:46.736",
            "finished": true
        },
        "usage": {
            "input_tokens": 29,
            "output_tokens": 477,
            "characters": 0,
            "size": "1280*1280",
            "total_tokens": 506,
            "image_count": 3
        }
    }
    ```

    Output statistics are 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`.
  </Tab>
</Tabs>

## DashScope Java SDK <span id="a5c3e8d7b9xyz" /> <span id="03c8f298aaz3m" />

SDK parameters align with the HTTP interface, encapsulated per language conventions.

The SDK handles asynchronous calls internally and supports both synchronous and asynchronous invocation.

> Actual duration depends on queue length and service load.

<Tip>
  Requires DashScope Java SDK <strong>version 2.22.6 or later</strong>.
</Tip>

The `base_url` and API key are not interchangeable across regions. Examples for the Singapore region:

<Tabs>
  <Tab title="Singapore">
    `https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="US (Virginia)">
    `https://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1`
  </Tab>

  <Tab title="China (Beijing)">
    `https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1`

    When calling, replace `{WorkspaceId}` with your actual [workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>

  <Tab title="Germany (Frankfurt)">
    `https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1`

    Replace `{WorkspaceId}` with your actual [Workspace ID](/en/model-studio/regions#h2_migrate_domain).
  </Tab>
</Tabs>

> The global deployment scope (Frankfurt region) only supports asynchronous calls.

### Image editing <span id="a89623b02bahd" /> <span id="7ec8584786694" />

<Tabs>
  <Tab title="Synchronous">
    ##### Request example <span id="d7f8a6b5c9yza" /> <span id="c9e6f5a4b8vwx" />

    ```java expandable
    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 {
            // Singapore region URL. Base URLs differ by region.
            Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
        }

        // If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
        // API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        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(
                            // Supports multi-image input; provide multiple reference images
                            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();

            // Image editing uses standard synchronous call; no need to set stream or enable_interleave
            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());
            }
        }
    }
    ```

    ##### Response example <span id="b8e9f7a6d5efg" /> <span id="a7d8e6f5c9cde" />

    > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "requestId": "b148327e-830f-414c-a8df-724dec28exxx",
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "total_tokens": 0,
            "image_count": 1,
            "size": "1376*768"
        },
        "output": {
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "finished": true
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
    ```
  </Tab>

  <Tab title="Asynchronous">
    ##### Request example <span id="b9e8f7d6a5klm" /> <span id="a8d9f7c6e5jkl" />

    ```java expandable
    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 - Asynchronous call example
     */
    public class Main {

        static {
            // Singapore region URL. Base URLs differ by region.
            Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
        }

        // If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
        // API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        static String apiKey = System.getenv("DASHSCOPE_API_KEY");

        public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException {
            // Build multi-image input message
            ImageGenerationMessage message = ImageGenerationMessage.builder()
                    .role("user")
                    .content(Arrays.asList(
                            // Supports multi-image input; provide multiple reference images
                            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")
                    .n(1)
                    .size("1K")
                    .negativePrompt("")
                    .promptExtend(true)
                    .messages(Arrays.asList(message))
                    .build();

            ImageGeneration imageGeneration = new ImageGeneration();
            ImageGenerationResult result = null;
            try {
                System.out.println("---async call for image editing, creating task----");
                result = imageGeneration.asyncCall(param);
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                throw new RuntimeException(e.getMessage());
            }
            System.out.println("Task creation result:");
            System.out.println(JsonUtils.toJson(result));

            String taskId = result.getOutput().getTaskId();
            // Wait for task completion
            waitTask(taskId);
        }

        public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
            ImageGeneration imageGeneration = new ImageGeneration();
            System.out.println("\n---waiting for task completion----");
            ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
            System.out.println("Task completion result:");
            System.out.println(JsonUtils.toJson(result));
        }

        public static void main(String[] args) {
            try {
                asyncCall();
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    ```

    ##### Response example <span id="a8c9f7e6b5pqr" /> <span id="f9a8b7e6d5opq" />

    1. Task creation response example

    ```json
    {
        "status_code": 200,
        "request_id": "9cd85950-2e26-4b2c-b562-1694cf928xxx",
        "code": "",
        "message": "",
        "output": {
            "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c313xxx",
            "task_status": "PENDING"
        },
        "usage": null
    }
    ```

    1. Task result query response example

       > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "status_code": 200,
        "request_id": "cbdf1424-306e-4a52-82f3-8bf5d8a99xxx",
        "code": "",
        "message": "",
        "output": {
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba",
            "task_status": "SUCCEEDED",
            "submit_time": "2026-01-16 16:36:06.556",
            "scheduled_time": "2026-01-16 16:36:06.591",
            "end_time": "2026-01-16 16:36:25.190",
            "finished": true
        },
        "usage": {
            "input_tokens": 0,
            "output_tokens": 0,
            "size": "1376*768",
            "total_tokens": 0,
            "image_count": 1
        }
    }
    ```
  </Tab>
</Tabs>

### Interleaved text-image output <span id="eecec85d17ql5" /> <span id="f80e930f554yt" />

<Tabs>
  <Tab title="Synchronous call (streaming only)">
    ##### Request example <span id="be34d558a0k0l" /> <span id="45880cfd9foul" />

    ```java expandable
    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 {
            // Singapore region URL. Base URLs differ by region.
            Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
        }

        // If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
        // API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        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);
        }
    }
    ```

    ##### Response example <span id="55f0d419c4pkv" /> <span id="a32adc6b3e7aq" />

    > URL expires after 24 hours. Download images promptly.

    ```json
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":0,"total_tokens":28,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"Chili"}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":1,"total_tokens":29,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"stir-fry"}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":2,"total_tokens":30,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"pork"}]}}],"finished":false},"status_code":200,"code":"","message":""}

    ......

    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":73,"total_tokens":101,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"."}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":198,"total_tokens":226,"image_count":1,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"image","image":"https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":199,"total_tokens":227,"image_count":1,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"Next"}]}}],"finished":false},"status_code":200,"code":"","message":""}

    ......

    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":245,"total_tokens":273,"image_count":1,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"."}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":368,"total_tokens":396,"image_count":2,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"image","image":"https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":369,"total_tokens":397,"image_count":2,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"Finally"}]}}],"finished":false},"status_code":200,"code":"","message":""}

    ......

    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":416,"total_tokens":444,"image_count":2,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"pot"}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":417,"total_tokens":445,"image_count":2,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"."}]}}],"finished":false},"status_code":200,"code":"","message":""}
    {"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":541,"total_tokens":569,"image_count":3,"size":"1280*1280"},"output":{"choices":[{"finish_reason":"stop","message":{"role":"assistant","content":[{"type":"image","image":"https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx"}]}}],"finished":true},"status_code":200,"code":"","message":""}
    ```
  </Tab>

  <Tab title="Asynchronous call">
    ##### Request example <span id="31bd2b2db4s5m" /> <span id="d1491924d0syi" />

    <strong>Note</strong>: Asynchronous calls do not require the stream parameter

    ```java expandable
    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.Collections;

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

        static {
            // Singapore region URL. Base URLs differ by region.
            Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
        }

        // If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
        // API keys differ by region. Get API key: https://www.alibabacloud.com/help/model-studio/get-api-key
        static String apiKey = System.getenv("DASHSCOPE_API_KEY");

        public static void asyncCall() 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();

            ImageGenerationParam param = ImageGenerationParam.builder()
                    .apiKey(apiKey)
                    .model("wan2.6-image")
                    .size("1280*1280")
                    .enableInterleave(true)
                    .maxImages(3)
                    .negativePrompt("")
                    .messages(Collections.singletonList(message))
                    .build();

            ImageGeneration imageGeneration = new ImageGeneration();
            ImageGenerationResult result = null;
            try {
                System.out.println("---async call for image interleave, creating task----");
                result = imageGeneration.asyncCall(param);
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                throw new RuntimeException(e.getMessage());
            }
            System.out.println("Task creation result:");
            System.out.println(JsonUtils.toJson(result));

            String taskId = result.getOutput().getTaskId();
            // Wait for task completion
            waitTask(taskId);
        }

        public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
            ImageGeneration imageGeneration = new ImageGeneration();
            System.out.println("\n---waiting for task completion----");
            ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
            System.out.println("Task completion result:");
            System.out.println(JsonUtils.toJson(result));
        }

        public static void main(String[] args) {
            try {
                asyncCall();
            } catch (ApiException | NoApiKeyException | UploadFileException e) {
                System.out.println(e.getMessage());
            }
        }
    }
    ```

    ##### Response example <span id="f8468ee4c3kwp" /> <span id="6047c725829i1" />

    1. Task creation response example

    ```json
    {
        "requestId": "7d6c5760-334b-48c4-9b1e-08ee9c7fexxx",
        "output": {
            "task_id": "1bb9d9fa-bf1a-43dc-b5fe-366c1dc70xxx",
            "task_status": "PENDING"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
    ```

    1. Task result query response example

       > URL expires after 24 hours. Download images promptly.

    ```json expandable
    {
        "requestId": "6ed62b00-2225-4fc3-8ee3-2aed0b484xxx",
        "usage": {
            "input_tokens": 29,
            "output_tokens": 471,
            "total_tokens": 500,
            "image_count": 3,
            "size": "1280*1280"
        },
        "output": {
            "choices": [
                {
                    "finish_reason": "stop",
                    "message": {
                        "role": "assistant",
                        "content": [
                            {
                                "text": "Stir-fried pork with chili peppers is a classic Hunan dish and a beloved home-cooked favorite for many. Known for its fresh spiciness and tender meat, it's simple to prepare yet delivers an exceptional flavor experience. Today, we'll learn how to make this dish.\n\nFirst, preparing all ingredients is the key to success. Fresh pork, red and green chili peppers, garlic cloves, and ginger slices are essential. Slice the pork thinly, cut the chilies into segments, and mince the garlic and ginger.",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            },
                            {
                                "text": "Next, marinate the pork. Place the sliced pork in a bowl, add a little light soy sauce, cooking wine, starch, and cooking oil. Mix well by hand and marinate for 10 to 15 minutes. This treatment makes the pork slices more tender and flavorful.",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            },
                            {
                                "text": "Finally, heat oil in a wok over high heat. Add the marinated pork slices and quickly stir-fry until they change color, then remove and set aside. Leave some oil in the wok, add minced garlic and ginger to release their aroma, then add chili segments and stir-fry until fragrant. Add the pork back in, season with light soy sauce, dark soy sauce, a pinch of sugar, and oyster sauce. Stir-fry quickly until evenly coated, sprinkle with chopped scallions, and serve.",
                                "type": "text"
                            },
                            {
                                "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                                "type": "image"
                            }
                        ]
                    }
                }
            ],
            "task_id": "1bb9d9fa-bf1a-43dc-b5fe-366c1dc70836",
            "task_status": "SUCCEEDED",
            "finished": true,
            "submit_time": "2026-01-16 18:26:32.082",
            "scheduled_time": "2026-01-16 18:26:32.133",
            "end_time": "2026-01-16 18:28:41.748"
        },
        "status_code": 200,
        "code": "",
        "message": ""
    }
    ```
  </Tab>
</Tabs>

## Limitations <span id="20263d27eeksq" /> <span id="d25cdaa55byma" />

- <strong>Data validity</strong>: The task `task_id` and image `url` are retained for only 24 hours. After this period, they cannot be queried or downloaded.
- <strong>Content moderation</strong>: Both the input `prompt` and output image undergo content moderation. Non-compliant content returns an `IPInfringementSuspect` or `DataInspectionFailed` error. See [Error codes](/en/model-studio/error-code).

## Billing and rate limiting <span id="5dafefe82bgrh" /> <span id="3cf59588a6pqu" />

- Free quotas and pricing: [Model pricing](/en/model-studio/model-pricing).
- For model rate limits, see [Wanxiang](/en/model-studio/rate-limit).
- You are charged per successfully generated image. Failed calls incur no charge and do not consume [free quota](/en/model-studio/new-free-quota).

## Error codes <span id="OajFO" /> <span id="167ca98729h1n" />

If the model call fails and returns an error message, see [Error codes](/en/model-studio/error-code) for resolution.

## FAQ <span id="ed3bed65cdp1s" /> <span id="c4e8985e53yrl" />

<strong>Q: How do I view a model's inference costs and call volume?</strong>

A: See [Bill inquiry and cost management](/en/model-studio/bill-query-and-cost-management).

<strong>Q: Why can't I run the code examples?</strong>

A: Upgrade your SDK to the latest version. [Install SDK](/en/model-studio/install-sdk).
