Wanx text-to-image V1 API reference

Updated at:

This topic describes the input and output parameters for the Wanx text-to-image V1 model.

Related guide: Text-to-image

Important

  • This document applies only to the China (Beijing) region. You must use an API key from this region.
  • We recommend using the fully upgraded text-to-image V2 model.

ImportantAlibaba Cloud Model Studio has released a workspace-specific domain for the China (Beijing) region: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com. The new dedicated domain delivers superior performance and higher stability for inference requests. We recommend migrating from https://dashscope.aliyuncs.com to the new domain.

{WorkspaceId} is your workspace ID, which can be found on the Workspace Details page in the Alibaba Cloud Model Studio console. The existing domain remains fully functional.

Model overview

Model overview

Model

Model overview

wanx-v1

The Wanx text-to-image large model, with main features including:

  • Supports bilingual input in Chinese and English.

  • Supports multiple image styles.

  • Supports reference image input for content or style transfer, enabling richer styles, themes, and genres.

For more information, see Model billing and rate limits.

Prerequisites

The text-to-image V1 model API supports calls via HTTP and the DashScope SDK.

Before calling, you need to obtain and configure an API Key, and then configure the API Key in environment variables.

To call via SDK, please install the DashScope SDK. Currently, the SDK supports Python and Java.

HTTP calls

Image models take longer to process. To avoid request timeouts, HTTP calls only support retrieving model results asynchronously. You need to make two requests:

  1. Create a task to get the task ID: First send a task creation request, which returns a task ID (task_id).
  2. Query results by task ID: Use the task ID obtained in the previous step to query the task status and results. When the task completes successfully, an image URL is returned, valid for 24 hours.

NoteAfter a task is created, it is added to a queue and waits to be scheduled for execution. You then need to call the "Query results by task ID" API to obtain the task status and results.

Step 1: Create a task to get the task ID

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis

When calling, replace {WorkspaceId} with your actual Workspace ID.

Request parameters

Request headers

Content-Typestring(required)

The request content type. This parameter must be set to application/json.

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

X-DashScope-Asyncstring(required)

Asynchronous processing configuration parameter. HTTP requests support asynchronous calls only; it must be set to enable.

ImportantIf this request header is missing, the following error will be reported: "current user api does not support synchronous calls".

X-DashScope-WorkSpacestring(Optional)

The Alibaba Cloud Model Studio Workspace ID. Example value: llm-xxxx.

You can obtain the Workspace ID here.

Detailed description

This parameter is filled in based on the Alibaba Cloud Model Studio API Key.

  • For a primary account API Key, this parameter is optional. If left empty, primary account permissions are used; if filled in, the permissions of the corresponding workspace are used.
  • For a RAM sub-account API Key, this parameter is required. RAM sub-accounts always belong to a workspace.

The workspace must have permission to access the model before the API can be called. If you do not have permission, see Authorize sub-workspace model calling, training, and deployment.

For information on how to distinguish between Alibaba Cloud Model Studio primary accounts and RAM sub-accounts, see Primary account management.

Request Body

modelstring(Required)

The model name. Example value: wanx-v1.

inputobject(Required)

The basic input information, such as prompts.

Properties

promptstring(Required)

The positive prompt, used to describe the elements and visual features that you want in the generated image.

Supports Chinese and English, up to 800 characters in length. Each Chinese character or letter counts as one character, and any excess is automatically truncated.

Example value: An orange tabby cat sitting down, with a pleasant expression, lively and adorable, realistic and accurate.

For tips on using prompts, see Text-to-image prompt guide.

negative_promptstring (Optional)

The negative prompt, used to describe the content you do not want in the image, which constrains the image.

Supports Chinese and English, up to 500 characters in length. Any excess is automatically truncated.

Example value: low resolution, errors, worst quality, low quality, deformities, extra fingers, bad proportions, etc.

ref_imgstring(Optional)

The URL of the reference image. The model generates an image with a similar style based on the reference image.

Image limits:

  • Image format: JPG, JPEG, PNG, BMP, TIFF, WEBP, and other common formats.
  • Image size: no more than 10 MB.
  • Image resolution: at least 256×256 pixels and no more than 4096×4096 pixels.
  • The URL must not contain Chinese characters.

parametersobject (Optional)

The image processing parameters.

Properties

style string (Optional)

The style of the output image. The following styles are supported:

Enumeration values

  • <auto>: Default value. The model randomly selects an image style.
  • <photography>: Photography.
  • <portrait>: Portrait.
  • <3d cartoon>: 3D cartoon.
  • <anime>: Animation.
  • <oil painting>: Oil painting.
  • <watercolor>: Watercolor.
  • <sketch>: Sketch.
  • <chinese painting>: Chinese painting.
  • <flat illustration>: Flat illustration.

size string (Optional)

The resolution of the output image. The following four image resolutions are currently supported:

Enumeration values

  • 1024*1024: Default value.
  • 720*1280
  • 768*1152
  • 1280*720

n integer (Optional)

The number of images to generate. The value must be an integer from 1 to 4. The default value is 4.

seed integer (Optional)

The random number seed, which is used to control the randomness of the generated content. The value must be in the range of [0, 2147483647].

If not provided, the algorithm automatically generates a random number as the seed. If provided, a seed parameter is generated for each of the n images based on the value of n; for example, with n=4, the algorithm generates images with seed, seed+1, seed+2, and seed+3 as their parameters respectively.

To ensure the generated content is relatively stable, use the same seed value for each request.

ref_strength float (Optional)

Controls the similarity between the output image and the reference image.

The value must be in the range of [0.0, 1.0]. A larger value indicates that the generated image is more similar to the reference image.

ref_mode string (Optional)

The mode for generating an image based on a reference image. The following modes are supported:

Enumeration values

  • repaint: Default value. Generates an image based on the content of the reference image.
  • refonly: Generates an image based on the style of the reference image.

Text-to-image

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1
    }
}'
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。",
        "negative_prompt": "不要使用红色元素"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1
    }
}'

Generation from a reference image

curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "一个英气的黑发女人,飞舞着金色的蝴蝶,背景中有若隐若现的水墨竹林,高细节,高质量。",
        "ref_image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1,
        "ref_strength": 1.0,
        "ref_mode": "repaint"
    }
}'
curl -X POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis \
    -H 'X-DashScope-Async: enable' \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
    "model": "wanx-v1",
    "input": {
        "prompt": "有一只黑色的小猫",
        "ref_image": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/gpqnqy/house.png"
    },
    "parameters": {
        "style": "<auto>",
        "size": "1024*1024",
        "n": 1,
        "ref_strength": 0.7,
        "ref_mode": "refonly"
    }
}'

dashscope CLI

export DASHSCOPE_API_KEY="your-api-key"
# 将 {WorkspaceId} 替换为业务空间ID,cn-beijing 替换为对应地域(新加坡: ap-southeast-1, 美东: us-east-1)
export DASHSCOPE_HTTP_BASE_URL="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
dashscope image-synthesis create -m wanx2.1-t2i-turbo -p "一只可爱的猫" -n 1

ImportantThe SDK Expert interactive assistant can accomplish the same development and troubleshooting in natural language. See

DashScope SDK Expert.

For the complete region table, see Base URL overview.

Response parameters

outputobject

The task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is queued
  • RUNNING: The task is being processed
  • SUCCEEDED: The task completed successfully
  • FAILED: The task failed
  • CANCELED: The task is canceled
  • UNKNOWN: The task does not exist or its status is unknown

request_idstring

Unique request identifier for tracing and troubleshooting.

codestring

Error code. Returned only for failed requests. See Error codes.

messagestring

Detailed error message. Returned only for failed requests. See Error codes.

Successful response

Please save the task_id, which is used to query the task status and results.

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

Error response

Task creation failed. See Error codes.

{
    "code": "InvalidApiKey",
    "message": "No API-key provided.",
    "request_id": "7438d53d-6eb8-4596-8835-xxxxxx"
}

Step 2: Query the result by task ID

GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}

Request parameters

Headers

Authorization string (Required)

Authenticates the request with a Model Studio API key. Example: Bearer sk-xxxx.

Path parameters

task_id string (Required)

The ID of the task.

Query task results

Please replace 86ecf553-d340-4e21-xxxxxxxxx with the actual task_id.

If you use a model in the Singapore region, replace base_url with https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx, where {WorkspaceId} must be replaced with the actual workspace ID.

curl -X GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"

Response parameters

outputobject

The task output information.

Properties

task_id string

The task ID. Valid for queries for 24 hours.

task_status string

The status of the task.

Enumeration values

  • PENDING: The task is queued
  • RUNNING: The task is being processed
  • SUCCEEDED: The task completed successfully
  • FAILED: The task failed
  • CANCELED: The task is canceled
  • UNKNOWN: The task does not exist or its status is unknown

task_metrics object

Statistics for the task result.

Properties

TOTAL integer

The total number of tasks.

SUCCEEDED integer

The number of successful tasks.

FAILED integer

The number of failed tasks.

results array of object

The list of task results, including image URLs, error messages in case of partial task failure.

Structure

{
    "results": [
        {
            "url": ""
        },
        {
            "code": "",
            "message": ""
        }
    ]
}

codestring

Error code. Returned only for failed requests. See Error codes.

messagestring

Detailed error message. Returned only for failed requests. See Error codes.

usage object

The output statistics. Only successful results are counted.

Properties

image_count integer

Number of images successfully generated. Billing: Cost = Number of images × Unit price.

request_idstring

Unique request identifier for tracing and troubleshooting.

Success response

Task data (task status and image URLs) is retained for only 24 hours and then automatically purged. Save generated images promptly.

{
    "request_id": "85eaba38-0185-99d7-8d16-4d9135238846",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/b2.png"
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 2,
            "FAILED": 0
        }
    },
    "usage": {
        "image_count": 2
    }
}

Failure response

If the task fails, task_status is set to FAILED, with an error code and message provided. See Error codes for troubleshooting.

{
    "request_id": "e5d70b02-ebd3-98ce-9fe8-759d7d7b107d",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "FAILED",
        "code": "InvalidParameter",
        "message": "The size is not match the allowed size ['1024*1024', '720*1280', '1280*720']",
        "task_metrics": {
            "TOTAL": 4,
            "SUCCEEDED": 0,
            "FAILED": 4
        }
    }
}

Partial failure response

The model can generate multiple images per task. If at least one succeeds, the task status is SUCCEEDED and URLs of successful images are returned. Failed images include a failure reason. Usage statistics count only successful results. See Error codes.

{
    "request_id": "85eaba38-0185-99d7-8d16-4d9135238846",
    "output": {
        "task_id": "86ecf553-d340-4e21-af6e-a0c6a421c010",
        "task_status": "SUCCEEDED",
        "results": [
            {
                "url": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/123/a1.png"
            },
            {
                "code": "InternalError.Timeout",
                "message": "An internal timeout error has occured during execution, please try again later or contact service support."
            }
        ],
        "task_metrics": {
            "TOTAL": 2,
            "SUCCEEDED": 1,
            "FAILED": 1
        }
    },
    "usage": {
        "image_count": 1
    }
}

DashScope SDK invocation

Make sure you have installed the latest version of the DashScope SDK. Otherwise, a runtime error may occur. For more information, see Install the SDK.

The DashScope SDK currently supports Python and Java.

The parameter names in the SDK are mostly consistent with those in the HTTP API. The parameter structure varies based on the SDK encapsulation for each language. For parameter descriptions, see HTTP invocation.

Because image model processing can be time-consuming, the underlying service is provided asynchronously. The SDK is encapsulated to support both synchronous and asynchronous invocation methods.

Python SDK invocation

Synchronous call

Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。"

print('----sync call, please wait a moment----')
try:
    job = client.images.generate(model='wanx-v1',
                                 prompt=prompt,
                                 n=1,
                                 style='<watercolor>',
                                 size='1024*1024')
    print('response: %s' % job)
    # 在当前目录下保存图片
    for url in job.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。"

# 上传参考图方式:url链接和本地路径二选一
# 使用公网url链接
ref_img = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
# 使用本地文件路径(传入后SDK会自动上传)
sketch_image_url = './girl.png'

print('----sync call, please wait a moment----')
try:
    job = client.images.generate(model='wanx-v1',
                                 prompt=prompt,
                                 n=1,
                                 style='<auto>',
                                 size='1024*1024',
                                 parameters={'ref_mode': 'repaint', 'ref_strength': 1.0},
                                 # 本地文件路径也可作为ref_img的值传入:
                                 # extra_input={'ref_img': sketch_image_url},
                                 extra_input={'ref_img': ref_img})
    print(job)
    # 保留图片到当前目录
    for url in job.image_urls:
        file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
        with open('./%s' % file_name, 'wb+') as f:
            f.write(requests.get(url).content)
except DashScopeError as e:
    print(f"HTTP返回码:{e.status_code}")
    print(f"错误码:{e.code}")
    print(f"错误信息:{e.message}")
    print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
Response example
{
    "request_id": "4126d9dd-e037-9f32-8d56-6d29ab3f9a06",
    "task_id": "b476bc4e-35c1-4c4e-a4d9-xxxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxxx.png"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Asynchronous call

Request example
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。"

def async_call():
    print('----create task----')
    task_info = create_async_task()
    if task_info is None:
        return
    print('----wait task done then save image----')
    wait_async_task(task_info)

# 创建异步任务
def create_async_task():
    try:
        job = client.images.jobs.create(model='wanx-v1',
                                        prompt=prompt,
                                        n=1,
                                        style='<watercolor>',
                                        size='1024*1024')
        print(job)
        return job
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
        return None

# 等待异步任务结束(指数退避轮询,默认总预算24小时)
def wait_async_task(task):
    try:
        done = client.images.jobs.wait(task)
        print(done)
        for url in done.image_urls:
            file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(url).content)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

# 获取异步任务信息
def fetch_task_status(task):
    try:
        snapshot = client.images.jobs.fetch(task.task_id)
        print(snapshot)
        print(snapshot.status)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

# 取消异步任务,只有处于PENDING状态的任务才可以取消
def cancel_task(task):
    try:
        job = client.images.jobs.cancel(task.task_id)
        print(job)
        print(job.status)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    async_call()
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
import dashscope
import os
from dashscope import DashScopeError

# 以下为华北2(北京)地域的配置。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的region取值不同。
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。"

# 上传参考图方式:url链接和本地路径二选一
# 使用公网url链接
ref_img = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png"
# 使用本地文件路径(传入后SDK会自动上传)
sketch_image_url = './girl.png'

def async_call():
    print('----create task----')
    task_info = create_async_task()
    if task_info is None:
        return
    print('----wait task done then save image----')
    wait_async_task(task_info)

# 创建异步任务
def create_async_task():
    try:
        job = client.images.jobs.create(model='wanx-v1',
                                        prompt=prompt,
                                        n=1,
                                        style='<auto>',
                                        size='1024*1024',
                                        parameters={'ref_mode': 'repaint', 'ref_strength': 1.0},
                                        # 本地文件路径也可作为ref_img的值传入:
                                        # extra_input={'ref_img': sketch_image_url},
                                        extra_input={'ref_img': ref_img})
        print(job)
        return job
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")
        return None

# 等待异步任务结束(指数退避轮询,默认总预算24小时)
def wait_async_task(task):
    try:
        done = client.images.jobs.wait(task)
        print(done)
        for url in done.image_urls:
            file_name = PurePosixPath(unquote(urlparse(url).path)).parts[-1]
            with open('./%s' % file_name, 'wb+') as f:
                f.write(requests.get(url).content)
    except DashScopeError as e:
        print(f"HTTP返回码:{e.status_code}")
        print(f"错误码:{e.code}")
        print(f"错误信息:{e.message}")
        print("请参考文档:https://help.aliyun.com/zh/model-studio/developer-reference/error-code")

if __name__ == '__main__':
    async_call()
Response example
  1. Example response for creating a task
{
    "request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
    "task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
    "status": "PENDING"
}
  1. Example response for querying a task result
{
    "request_id": "d861d3ba-4b29-9491-abad-266ef4fb2f08",
    "task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
    "status": "SUCCEEDED",
    "results": [
        {
            "url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
        }
    ],
    "task_metrics": {
        "TOTAL": 1,
        "SUCCEEDED": 1,
        "FAILED": 0
    },
    "usage": {
        "image_count": 1
    }
}

Java SDK invocation

Synchronous call

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}
    public static void basicCall() throws ApiException, NoApiKeyException {
        String prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<watercolor>")
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void listTask() throws ApiException, NoApiKeyException {
        ImageSynthesis is = new ImageSynthesis();
        AsyncTaskListParam param = AsyncTaskListParam.builder().build();
        ImageSynthesisListResult result = is.list(param);
        System.out.println(result);
    }

    public void fetchTask() throws ApiException, NoApiKeyException {
        String taskId = "your task id";
        ImageSynthesis is = new ImageSynthesis();
        // If set DASHSCOPE_API_KEY environment variable, apiKey can null.
        ImageSynthesisResult result = is.fetch(taskId, null);
        System.out.println(result.getOutput());
        System.out.println(result.getUsage());
    }

    public static void main(String[] args){
        try{
            basicCall();
            //listTask();
        }catch(ApiException|NoApiKeyException e){
            System.out.println(e.getMessage());
        }
    }
}
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

import java.util.HashMap;

public class Main {
    // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void syncCall() {
        String prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。";
        //使用公网url链接
        String refImage = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png";
        HashMap<String,Object> parameters = new HashMap<>();
        parameters.put("ref_strength", 0.5);
        parameters.put("ref_mode", "repaint");

        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<auto>")
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .parameters(parameters)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            System.out.println("---sync call, please wait a moment----");
            result = imageSynthesis.call(param);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.syncCall();
    }

}
Response example
{
	"request_id": "150edcda-05d5-9ffe-8803-84626d1db623",
	"output": {
		"task_id": "f2098ff0-146e-404c-bb25-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
		}],
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Asynchronous call

Request example
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }

    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<watercolor>")
                        .n(1)
                        .size("1024*1024")
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }

    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            //环境变量配置后,可在这里将apiKey设置为null
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        System.out.println(JsonUtils.toJson(result));
        System.out.println(JsonUtils.toJson(result.getOutput()));
    }

    public static void main(String[] args){
        Main main = new Main();
        main.asyncCall();
    }
}
// Copyright (c) Alibaba, Inc. and its affiliates.

import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    // 以下为华北2(北京)地域的URL。请将 {WorkspaceId} 替换为您的百炼业务空间ID,各地域的URL不同。
    static {Constants.baseHttpApiUrl="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";}

    public void asyncCall() {
        System.out.println("---create task----");
        String taskId = this.createAsyncTask();
        System.out.println("---wait task done then return image url----");
        this.waitAsyncTask(taskId);
    }

    /**
     * 创建异步任务
     * @return taskId
     */
    public String createAsyncTask() {
        String prompt = "近景镜头,18岁的中国女孩,古代服饰,圆脸,正面看着镜头,民族优雅的服装,商业摄影,室外,电影级光照,半身特写,精致的淡妆,锐利的边缘。";
        String refImage = "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241031/rguyzt/girl.png";
        ImageSynthesisParam param =
                ImageSynthesisParam.builder()
                        .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                        .model(ImageSynthesis.Models.WANX_V1)
                        .prompt(prompt)
                        .style("<auto>")
                        .n(1)
                        .size("1024*1024")
                        .refImage(refImage)
                        .build();

        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            result = imageSynthesis.asyncCall(param);
        } catch (ApiException | NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }
        String taskId = result.getOutput().getTaskId();
        System.out.println("taskId=" + taskId);
        return taskId;
    }

    /**
     * 等待异步任务结束
     * @param taskId 任务id
     * */
    public void waitAsyncTask(String taskId) {
        ImageSynthesis imageSynthesis = new ImageSynthesis();
        ImageSynthesisResult result = null;
        try {
            // If you have set the DASHSCOPE_API_KEY in the system environment variable, the apiKey can be null.
            result = imageSynthesis.wait(taskId, null);
        } catch (ApiException|NoApiKeyException e){
            throw new RuntimeException(e.getMessage());
        }

        System.out.println(JsonUtils.toJson(result.getOutput()));
    }

    public static void main(String[] args){
        Main text2Image = new Main();
        text2Image.asyncCall();
    }
}
Response example
  1. Example response for creating a task
{
	"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "PENDING"
	}
}
  1. Example response for querying a task result
{
	"request_id": "c44213ba-7aa3-91e4-97c1-c527ade82597",
	"output": {
		"task_id": "7277e20e-aa01-4709-xxxxxxxx",
		"task_status": "SUCCEEDED",
		"results": [{
			"url": "https://dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com/xxxx.png"
		}],
		"task_metrics": {
			"TOTAL": 1,
			"SUCCEEDED": 1,
			"FAILED": 0
		}
	},
	"usage": {
		"image_count": 1
	}
}

Image output storage domains

The Tongyi Wan image generation service stores generated images in OSS, and the domain in the generated result URL varies by region. If your corporate network environment has egress whitelist restrictions, you must add the following OSS domains to the whitelist to retrieve the generated images.

The egress domains of the following 10 regions are currently supported:

Region

OSS domain

China (Beijing)

dashscope-result-bj.oss-cn-beijing.aliyuncs.com

China (Hangzhou)

dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com

China (Shanghai)

dashscope-result-sh.oss-cn-shanghai.aliyuncs.com

China (Ulanqab)

dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com

China (Zhangjiakou)

dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com

China (Shenzhen)

dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com

China (Heyuan)

dashscope-result-hy.oss-cn-heyuan.aliyuncs.com

China (Chengdu)

dashscope-result-cd.oss-cn-chengdu.aliyuncs.com

China (Guangzhou)

dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com

China (Ulanqab) ACDR

dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com

Error codes

If a model call fails and returns an error message, see Error messages for a solution.

FAQ

Model billing and rate limiting

Free quota
  • Description: The free quota applies only to successfully generated output images. Input images or failed model processing do not consume the free quota.
  • How to get: It is automatically granted when you activate Model Studio. Valid for 90 days.
  • Account scope: Shared between your Alibaba Cloud account and its RAM users.
  • For more details, see Free quota for new users.
Limited-time free trial
  • If billing shows a limited-time free trial, the model is in public preview. You cannot use the model after the free quota runs out.
Billing details
  • If a clear unit price is shown — for example, CNY 0.2 per second — the model is commercially available. You must pay after the free quota expires or is fully consumed.
  • Billing scope: Charges apply only to successfully generated output images. Other scenarios are not billed.
  • Billing method: Billing is applied to your Alibaba Cloud account. RAM users cannot be billed independently. Your Alibaba Cloud account must cover all associated charges. To view billing information, go to the Bills page.
  • Recharge: Go to the Expenses and Costs console.
  • View invocation metrics: Go to the Monitoring page.
  • For more billing questions, see Billing Items.
Rate limiting
  • Rate limit scope: Shared between your Alibaba Cloud account and its RAM users.