通義萬相-文生圖模型基於文本產生映像,支援多種藝術風格與寫實攝影效果,滿足多樣化創意需求。
通義萬相官網的功能與API支援的能力可能存在差異。本文檔以API的實際能力為準,並會隨功能更新及時同步。
前提條件
在調用前,先擷取API Key,再配置API Key到環境變數(準備下線,併入配置 API Key)。如需通過SDK進行調用,請安裝DashScope SDK。
新加坡、維吉尼亞和北京地區擁有獨立的 API Key 與請求地址,不可混用,跨地區調用將導致鑒權失敗或服務報錯,詳情請參見選擇地區和部署模式。
HTTP同步調用(wan2.6)
本章節介面為新版協議,僅支援 wan2.6模型。
一次請求即可獲得結果,流程簡單,推薦大多數情境使用。
新加坡地區:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
維吉尼亞地區:POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
北京地區:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
請求參數 | 文生圖 |
要求標頭(Headers) | |
Content-Type 請求內容類型。此參數必須設定為 | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
請求體(Request Body) | |
model 模型名稱。樣本值:wan2.6-t2i。 說明 wan2.5及以下版本模型,HTTP調用請參見HTTP非同步呼叫。 | |
input 輸入的基本資料。 | |
parameters 影像處理參數。 |
響應參數 | 任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。 任務執行異常如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
usage 輸出資訊統計。只對成功的結果計數。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 | |
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊。 | |
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊。 |
HTTP非同步呼叫(wan2.6)
本章節介面為新版協議,僅支援 wan2.6模型。
適用於對逾時敏感的情境。整個流程包含 “建立任務 -> 輪詢擷取” 兩個核心步驟,具體如下:
步驟1:建立任務擷取任務ID
新加坡地區:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image-generation/generation
維吉尼亞地區:POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation
北京地區:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation
建立成功後,使用介面返回的
task_id查詢結果,task_id 有效期間為 24 小時。請勿重複建立任務,輪詢擷取即可。
請求參數 | 文生圖 |
要求標頭(Headers) | |
Content-Type 請求內容類型。此參數必須設定為 | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
X-DashScope-Async 非同步處理配置參數。HTTP請求只支援非同步,必須設定為 重要 缺少此要求標頭將報錯:“current user api does not support synchronous calls”。 | |
請求體(Request Body) | |
model 模型名稱。樣本值:wan2.6-t2i。 說明 wan2.5及以下版本模型,HTTP調用請參見HTTP非同步呼叫。 | |
input 輸入的基本資料。 | |
parameters 影像處理參數。 |
響應參數 | 成功響應請儲存 task_id,用於查詢任務狀態與結果。 異常響應建立任務失敗,請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 | |
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊。 | |
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊。 |
步驟2:根據任務ID查詢結果
新加坡地區:GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
維吉尼亞地區:GET https://dashscope-us.aliyuncs.com/api/v1/tasks/{task_id}
北京地區:GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
輪詢建議:映像產生過程約需數分鐘,建議採用輪詢機制,並設定合理的查詢間隔(如 10 秒)來擷取結果。
任務狀態流轉:PENDING(排隊中)→ RUNNING(處理中)→ SUCCEEDED(成功)/ FAILED(失敗)。
結果連結:任務成功後返回映像連結,有效期間為 24 小時。建議在擷取連結後立即下載並轉存至永久儲存(如阿里雲 OSS)。
請求參數 | 查詢任務結果將 |
要求標頭(Headers) | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
URL路徑參數(Path parameters) | |
task_id 任務ID。 |
響應參數 | 任務執行成功任務資料(如任務狀態、映像URL等)僅保留24小時,逾時後會被自動清除。請您務必及時儲存產生的映像。 任務執行異常如果因為某種原因導致任務執行失敗,將返回相關資訊,可以通過code和message欄位明確指示錯誤原因。請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
usage 輸出資訊統計。只對成功的結果計數。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 | |
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊。 | |
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊。 |
HTTP非同步呼叫(wan2.5及以下版本模型)
此介面為舊版協議,僅支援wan2.5及以下版本模型。
由於文生圖任務耗時較長(通常為1-2分鐘),API採用非同步呼叫。整個流程包含 “建立任務 -> 輪詢擷取” 兩個核心步驟,具體如下:
具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。
步驟1:建立任務擷取任務ID
新加坡地區:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
北京地區:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
建立成功後,使用介面返回的
task_id查詢結果,task_id 有效期間為 24 小時。請勿重複建立任務,輪詢擷取即可。
請求參數 | 文生圖新加坡和北京地區的API Key不同,擷取API Key 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis 文生圖(使用反向提示詞)通過 negative_prompt 指定產生的圖片避免出現“人物”元素。 新加坡和北京地區的API Key不同,擷取API Key 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis |
要求標頭(Headers) | |
Content-Type 請求內容類型。此參數必須設定為 | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
X-DashScope-Async 非同步處理配置參數。HTTP請求只支援非同步,必須設定為 重要 缺少此要求標頭將報錯:“current user api does not support synchronous calls”。 | |
請求體(Request Body) | |
model 模型名稱。文生圖模型請參見模型列表。 樣本值:wan2.5-t2i-preview。 | |
input 輸入的基本資料,如提示詞等。 | |
parameters 影像處理參數。如設定映像解析度、開啟prompt智能改寫、添加浮水印等。 |
響應參數 | 成功響應請儲存 task_id,用於查詢任務狀態與結果。 異常響應建立任務失敗,請參見錯誤資訊進行解決。 |
output 任務輸出資訊。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 | |
code 請求失敗的錯誤碼。請求成功時不會返回此參數,詳情請參見錯誤資訊。 | |
message 請求失敗的詳細資料。請求成功時不會返回此參數,詳情請參見錯誤資訊。 |
步驟2:根據任務ID查詢結果
新加坡地區:GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
北京地區:GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
輪詢建議:映像產生過程約需數分鐘,建議採用輪詢機制,並設定合理的查詢間隔(如 10 秒)來擷取結果。
任務狀態流轉:PENDING(排隊中)→ RUNNING(處理中)→ SUCCEEDED(成功)/ FAILED(失敗)。
結果連結:任務成功後返回映像連結,有效期間為 24 小時。建議在擷取連結後立即下載並轉存至永久儲存(如阿里雲 OSS)。
請求參數 | 查詢任務結果請將 各地區的API Key不同。擷取API Key。 若使用北京地區的模型,需將base_url替換為https://dashscope.aliyuncs.com/api/v1/tasks/86ecf553-d340-4e21-xxxxxxxxx |
要求標頭(Headers) | |
Authorization 請求身份認證。介面使用阿里雲百鍊API-Key進行身份認證。樣本值:Bearer sk-xxxx。 | |
URL路徑參數(Path parameters) | |
task_id 任務ID。 |
響應參數 | 任務執行成功映像URL僅保留24小時,逾時後會被自動清除,請及時儲存產生的映像。 任務執行失敗若任務執行失敗,task_status將置為 FAILED,並提供錯誤碼和資訊。請參見錯誤資訊進行解決。 任務部分失敗模型可以在一次任務中產生多張圖片。只要有一張圖片產生成功,任務狀態將標記為 任務查詢到期task_id查詢有效期間為 24 小時,逾時後將無法查詢,返回以下報錯資訊。 |
output 任務輸出資訊。 | |
usage 輸出資訊統計。只對成功的結果計數。 | |
request_id 請求唯一標識。可用於請求明細溯源和問題排查。 |
DashScope Python SDK調用
SDK 的參數命名與HTTP介面基本一致,參數結構根據語言特性進行封裝。
由於文生圖任務耗時較長,SDK 在底層封裝了 HTTP 非同步呼叫流程,支援同步、非同步兩種調用方式。
具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。
wan2.6
以下代碼僅適合 wan2.6 模型。
請確保 DashScope Python SDK 版本不低於
1.25.7,再運行以下代碼。更新請參考安裝SDK。
各地區的base_url和 API Key 不通用,以下樣本以新加坡地區為例進行調用:
新加坡地區:https://dashscope-intl.aliyuncs.com/api/v1
維吉尼亞地區:https://dashscope-us.aliyuncs.com/api/v1
北京地區:https://dashscope.aliyuncs.com/api/v1
同步調用
請求樣本
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# 以下為新加坡地區base_url,各地區的base_url不同
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
content=[
{
'text': '一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵'
}
]
)
print("----sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(rsp)
響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"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": "1280*1280",
"total_tokens": 0
}
}非同步呼叫
請求樣本
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Role, Message
from http import HTTPStatus
# 以下為新加坡地區base_url,各地區的base_url不同
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# 建立非同步任務
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[{'text': '一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵'}]
)
response = ImageGeneration.async_call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
if response.status_code == 200:
print("Task created successfully:", response)
return response
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# 等待任務完成
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}")
# 擷取非同步任務資訊
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}")
# 取消非同步任務
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}")
# 主執行流程
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
響應樣本
1、建立任務的響應樣本
{
"status_code": 200,
"request_id": "c4f11410-ea42-4996-957d-9c82f9xxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": null,
"audio": null,
"task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx",
"task_status": "PENDING"
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0
}
}2、查詢任務結果的響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "7e57e7e8-00b0-4534-9aff-fe31e0xxxxxx",
"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": "f470bbfd-d955-4165-935b-d35b8exxxxxx",
"task_status": "SUCCEEDED",
"submit_time": "2026-01-09 17:18:17.901",
"scheduled_time": "2026-01-09 17:18:17.941",
"end_time": "2026-01-09 17:18:45.544",
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0,
"size": "1280*1280",
"total_tokens": 0,
"image_count": 1
}
}wan2.5及以下版本模型
以下代碼僅適合wan2.5及以下版本模型。
請確保 DashScope Python SDK 版本不低於
1.25.2,再運行以下代碼。若版本過低,可能會觸發 “url error, please check url!” 等錯誤。請參考安裝SDK進行更新。
各地區的base_url和 API Key 不通用,以下樣本以新加坡地區為例進行調用:
新加坡地區:https://dashscope-intl.aliyuncs.com/api/v1
北京地區:https://dashscope.aliyuncs.com/api/v1
同步調用
請求樣本
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
print('----sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# 在目前的目錄下儲存圖片
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png",
"orig_prompt": "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
"actual_prompt": "一間精緻的花店,窗戶上裝飾著優雅的雕花,漂亮的木質門上掛著銅製把手。店內擺放著各種色彩鮮豔的花朵,如玫瑰、鬱金香和百合等。背景是溫馨的室內情境,光線柔和,營造出寧靜舒適的氛圍。高清寫實攝影,近景中心構圖。"
}],
"submit_time": "2025-01-08 19:36:01.521",
"scheduled_time": "2025-01-08 19:36:01.542",
"end_time": "2025-01-08 19:36:13.270",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
非同步呼叫
請求樣本
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def async_call():
print('----create task----')
task_info = create_async_task()
print('----wait task done then save image----')
wait_async_task(task_info)
# 建立非同步任務
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# 等待非同步任務結束
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# save file to current directory
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# 擷取非同步任務資訊
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# 取消非同步任務,只有處於PENDING狀態的任務才可以取消
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
響應樣本
1、建立任務的響應樣本
{
"status_code": 200,
"request_id": "31b04171-011c-96bd-ac00-f0383b669cc7",
"code": "",
"message": "",
"output": {
"task_id": "4f90cf14-a34e-4eae-xxxxxxxx",
"task_status": "PENDING",
"results": []
},
"usage": null
}2、查詢任務結果的響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png",
"orig_prompt": "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
"actual_prompt": "一間精緻的花店,窗戶上裝飾著優雅的雕花,漂亮的木質門上掛著銅製把手。店內擺放著各種色彩鮮豔的花朵,如玫瑰、鬱金香和百合等。背景是溫馨的室內情境,光線柔和,營造出寧靜舒適的氛圍。高清寫實攝影,近景中心構圖。"
}],
"submit_time": "2025-01-08 19:36:01.521",
"scheduled_time": "2025-01-08 19:36:01.542",
"end_time": "2025-01-08 19:36:13.270",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
DashScope Java SDK調用
SDK 的參數命名與HTTP介面基本一致,參數結構根據語言特性進行封裝。
由於文生圖任務耗時較長,SDK 在底層封裝了 HTTP 非同步呼叫流程,支援同步、非同步兩種調用方式。
具體耗時受限於排隊任務數和服務執行情況,請在擷取結果時耐心等待。
wan2.6
以下代碼僅適合 wan2.6-t2i 模型。
請確保 DashScope Java SDK 版本不低於
2.22.6,再運行以下代碼。
各地區的base_url和 API Key 不通用,以下樣本以新加坡地區為例進行調用:
新加坡地區:https://dashscope-intl.aliyuncs.com/api/v1
維吉尼亞地區:https://dashscope-us.aliyuncs.com/api/v1
北京地區:https://dashscope.aliyuncs.com/api/v1
同步調用
請求樣本
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;
public class Main {
static {
// 以下為新加坡地區url,各地區的base_url不同
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call, please 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());
}
}
}響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
"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"
}
]
}
}
],
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}非同步呼叫
請求樣本
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;
public class Main {
static {
// 以下為新加坡地區url,各地區的base_url不同
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/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", "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---async call, creating task----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// 等待任務完成
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
asyncCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}響應樣本
1、建立任務的響應樣本
{
"status_code": 200,
"request_id": "9cd85950-2e26-4b2c-b562-1694cf9288e5",
"code": "",
"message": "",
"output": {
"task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba",
"task_status": "PENDING"
},
"usage": null
}2、查詢任務結果的響應樣本
url 有效期間24小時,請及時下載映像。
{
"status_code": 200,
"request_id": "cbdf1424-306e-4a52-82f3-8bf5d8a99103",
"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": "1280*1280",
"total_tokens": 0,
"image_count": 1
}
}wan2.5及以下版本模型
wan2.6-t2i模型暫不支援 Java SDK調用。以下代碼僅適合wan2.5及以下版本模型。請確保 DashScope Java SDK 版本不低於
2.22.2,再運行以下代碼。若版本過低,可能會觸發 “url error, please check url!” 等錯誤。請參考安裝SDK進行更新。
各地區的base_url和 API Key 不通用,以下樣本以新加坡地區為例進行調用:
新加坡地區:https://dashscope-intl.aliyuncs.com/api/v1
北京地區:https://dashscope.aliyuncs.com/api/v1
同步調用
請求樣本
// 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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
// 設定parameters參數
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵")
.n(1)
.size("1280*1280")
.negativePrompt("")
.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 listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
// If set DASHSCOPE_API_KEY environment variable, apiKey can null.
ImageSynthesisResult result = is.fetch(taskId, apiKey);
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());
}
}
}響應樣本
url 有效期間24小時,請及時下載映像。
{
"request_id": "22f9c744-206c-9a78-899a-xxxxxx",
"output": {
"task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"orig_prompt": "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
"actual_prompt": "一間有著精緻雕花窗戶的花店,漂亮的深色木質門微微敞開。店內擺放著各式各樣的鮮花,包括玫瑰、百合和向日葵,色彩鮮豔,香氣撲鼻。背景是溫馨的室內情境,光線柔和,透過窗戶灑在花朵上。高清寫實攝影,中景構圖。",
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png"
}],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}非同步呼叫
請求樣本
// 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.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey="sk-xxx"
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
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() {
// 設定parameters參數
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵")
.n(1)
.size("1280*1280)
.negativePrompt("")
.parameters(parameters)
.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, apiKey);
} 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();
}
}響應樣本
1、建立任務的響應樣本
{
"request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8",
"output": {
"task_id": "7277e20e-aa01-4709-xxxxxxxx",
"task_status": "PENDING"
}
}2、查詢任務結果的響應樣本
{
"request_id": "22f9c744-206c-9a78-899a-xxxxxx",
"output": {
"task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"orig_prompt": "一間有著精緻窗戶的花店,漂亮的木質門,擺放著花朵",
"actual_prompt": "一間有著精緻雕花窗戶的花店,漂亮的深色木質門微微敞開。店內擺放著各式各樣的鮮花,包括玫瑰、百合和向日葵,色彩鮮豔,香氣撲鼻。背景是溫馨的室內情境,光線柔和,透過窗戶灑在花朵上。高清寫實攝影,中景構圖。",
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png"
}],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}使用限制
資料時效:任務
task_id和 映像url均只保留 24 小時,到期後將無法查詢或下載。內容審核:輸入的
prompt和輸出的映像均會經過Alibaba Content Security Service審核,包含違規內容的請求將報錯“IPInfringementSuspect”或“DataInspectionFailed”,具體參見錯誤資訊。網路訪問配置:映像連結儲存於阿里雲 OSS,如果業務系統因安全性原則無法訪問外部OSS連結,請將以下 OSS 網域名稱加入網路訪問白名單。
# OSS網域名稱列表 dashscope-result-bj.oss-cn-beijing.aliyuncs.com dashscope-result-hz.oss-cn-hangzhou.aliyuncs.com dashscope-result-sh.oss-cn-shanghai.aliyuncs.com dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com dashscope-result-zjk.oss-cn-zhangjiakou.aliyuncs.com dashscope-result-sz.oss-cn-shenzhen.aliyuncs.com dashscope-result-hy.oss-cn-heyuan.aliyuncs.com dashscope-result-cd.oss-cn-chengdu.aliyuncs.com dashscope-result-gz.oss-cn-guangzhou.aliyuncs.com dashscope-result-wlcb-acdr-1.oss-cn-wulanchabu-acdr-1.aliyuncs.com
計費與限流
錯誤碼
如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。
常見問題
Q: 如何查看模型的推理費用和調用量?
A: 詳情請參見賬單查詢與成本管理。