Model pembuatan gambar Wan mendukung image editing dan mixed text-and-image output untuk memenuhi berbagai kebutuhan pembuatan dan integrasi.
Ikhtisar model
Model | Deskripsi | Spesifikasi gambar output |
wan2.6-image | Wan2.6 image Mendukung image editing dan mixed text-and-image output. | Format gambar: PNG. Untuk resolusi dan dimensi gambar, lihat parameter size. |
Sebelum melakukan pemanggilan, lihat daftar model dan harga untuk setiap wilayah.
Prasyarat
Anda harus mendapatkan Kunci API dan menyetel Kunci API sebagai Variabel lingkungan.
Wilayah Singapura, Virginia, dan Beijing memiliki Kunci API dan titik akhir permintaan yang terpisah. Jangan menggunakannya secara bergantian karena pemanggilan lintas-wilayah dapat menyebabkan kegagalan autentikasi atau kesalahan layanan. Untuk detail selengkapnya, lihat Pilih wilayah dan mode penyebaran.
Pemanggilan HTTP sinkron
Dapatkan hasil dalam satu permintaan—proses sederhana ini direkomendasikan untuk sebagian besar skenario.
Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
AS (Virginia): POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
China (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Parameter permintaan | Image editingMixed text-and-image output (streaming only)Saat mixed text-and-image output diaktifkan (yaitu,
|
Headers | |
Content-Type Tipe konten permintaan. Harus berupa | |
Authorization Kredensial autentikasi menggunakan Kunci API Model Studio. Contoh: | |
X-DashScope-Sse Mengaktifkan streaming output.
| |
Request Body | |
model Nama model. Setel ke wan2.6-image. | |
input Informasi input dasar. | |
parameters Parameter pengeditan gambar. |
Parameter respons | Tugas berhasilData tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam, lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan. Tugas berhasil (streaming output)Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam, lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan. Kesalahan tugasJika tugas gagal dieksekusi, informasi dikembalikan, dan field code serta message secara jelas menunjukkan penyebab kesalahan. Untuk menyelesaikan masalah tersebut, lihat Pesan kesalahan. |
output Informasi output tugas. | |
usage Statistik untuk output. Hanya hasil yang berhasil yang dihitung. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah. | |
code Kode kesalahan. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. | |
message Pesan kesalahan detail. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. |
Pemanggilan HTTP asinkron
Tugas pembuatan gambar bisa memakan waktu lama, biasanya 1 hingga 2 menit. Gunakan pemanggilan asinkron untuk menghindari timeout permintaan. Seluruh proses melibatkan dua langkah inti: Buat Tugas -> Polling untuk Hasil. Langkah-langkahnya sebagai berikut:
Waktu spesifik yang dibutuhkan tergantung pada jumlah tugas dalam antrian dan status eksekusi layanan. Harap bersabar saat mengambil hasilnya.
Langkah 1: Buat tugas untuk mendapatkan ID tugas
Singapura: POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/image-generation/generation
AS (Virginia): POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation
China (Beijing): POST https://dashscope.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Setelah tugas dibuat, gunakan
task_idyang dikembalikan untuk menanyakan hasilnya.task_idberlaku selama 24 jam. Jangan membuat tugas duplikat. Sebaliknya, gunakan polling untuk mengambil hasilnya.Untuk tutorial pemula, lihat Postman.
Parameter permintaan | Image editingMixed text-and-image output |
Headers | |
Content-Type Tipe konten permintaan. Harus berupa | |
Authorization Kredensial autentikasi menggunakan Kunci API Model Studio. Contoh: | |
X-DashScope-Async Parameter konfigurasi pemrosesan asinkron. Harus disetel ke Penting Jika Anda menghilangkan header ini, kesalahan dikembalikan: "current user api does not support synchronous calls". | |
Request Body | |
model Nama model. Contoh: wan2.6-image. | |
input Informasi input dasar. | |
parameters Parameter pengeditan gambar. |
Parameter respons | Respons berhasilSimpan Respons kesalahanPembuatan tugas gagal. Lihat kode kesalahan untuk menyelesaikan masalah. |
output Informasi output tugas. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan pemecahan masalah. | |
code Kode kesalahan. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. | |
message Pesan kesalahan detail. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. |
Langkah 2: Tanyakan hasil berdasarkan ID tugas
Singapura: GET https://dashscope-intl.aliyuncs.com/api/v1/tasks/{task_id}
Virginia: GET https://dashscope-us.aliyuncs.com/api/v1/tasks/{task_id}
Beijing: GET https://dashscope.aliyuncs.com/api/v1/tasks/{task_id}
Rekomendasi polling: Pembuatan gambar merupakan proses yang memakan waktu. Kami menyarankan menggunakan mekanisme polling dengan interval permintaan yang wajar, misalnya setiap 10 detik, untuk mengambil hasilnya.
Alur status tugas: PENDING → RUNNING → SUCCEEDED / FAILED.
Tautan hasil: Tugas yang berhasil akan mengembalikan tautan gambar yang berlaku selama 24 jam. Segera unduh dan pindahkan gambar ke penyimpanan permanen, seperti Object Storage Service (OSS), setelah menerima tautannya.
Parameter permintaan | Hasil Kueri TugasGanti |
Headers | |
Authorization Kredensial autentikasi menggunakan Kunci API Model Studio. Contoh: | |
Parameter path URL | |
task_id ID tugas yang akan ditanyakan. |
Parameter respons | Tugas berhasilData tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam, lalu dihapus secara otomatis. Segera simpan gambar yang dihasilkan. Kesalahan tugasJika eksekusi tugas gagal, respons akan mencakup field code dan message yang menjelaskan penyebab kesalahan. Lihat Pesan kesalahan untuk solusinya. |
output Informasi output tugas. | |
usage Statistik untuk output. Hanya hasil yang berhasil yang dihitung. | |
request_id Pengidentifikasi unik untuk permintaan. Gunakan untuk pelacakan dan troubleshooting masalah. | |
code Kode kesalahan. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. | |
message Pesan kesalahan detail. Dikembalikan hanya saat permintaan gagal. Lihat kode kesalahan untuk detailnya. |
DashScope Python SDK
Penamaan parameter SDK sebagian besar konsisten dengan HTTP API, tetapi struktur parameternya dienkapsulasi sesuai karakteristik bahasa pemrograman.
Karena tugas bisa memakan waktu lama, SDK mengenkapsulasi proses pemanggilan HTTP asinkron dan mendukung metode pemanggilan sinkron maupun asinkron.
Waktu spesifik yang dibutuhkan tergantung pada jumlah tugas dalam antrian dan status eksekusi layanan. Harap bersabar saat mengambil hasilnya.
Sebelum menjalankan kode berikut, pastikan versi DashScope Python SDK Anda adalah 1.25.8 atau lebih baru. Untuk memperbarui SDK, lihat Instal SDK.
Parameter base_url dan Kunci API berbeda untuk setiap wilayah. Contoh berikut menunjukkan cara melakukan pemanggilan di wilayah Singapura:
Singapura: https://dashscope-intl.aliyuncs.com/api/v1
Virginia: https://dashscope-us.aliyuncs.com/api/v1
Beijing: https://dashscope.aliyuncs.com/api/v1
Image editing
Pemanggilan sinkron
Contoh permintaan
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
# File lokal didukung, contohnya, "image": "file://umbrella1.png"
content=[
{
"text": "Generate an image of scrambled eggs with tomatoes using 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, please 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="1280*1280"
)
print(rsp)Contoh respons
Tautan berlaku selama 24 jam. Unduh gambar segera.
{
"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": "1280*1280",
"total_tokens": 0
}
}Pemanggilan asinkron
Contoh permintaan
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Buat tugas asinkron
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[
{'text': 'Generate an image of scrambled eggs with tomatoes using 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="1280*1280"
)
if response.status_code == 200:
print("Task created successfully:", response)
return response # Kembalikan ID tugas
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# Tunggu hingga tugas selesai
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}")
# Ambil informasi tugas
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}")
# Batalkan tugas asinkron
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}")
# Alur eksekusi utama
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
Contoh respons
1. Contoh respons saat membuat tugas
{
"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
}
}2. Contoh respons saat menanyakan hasil tugas
Tautan berlaku selama 24 jam. Unduh gambar segera.
{
"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": "1280*1280",
"total_tokens": 0,
"image_count": 1
}
}Mixed text-and-image output
Pemanggilan sinkron (hanya streaming)
Contoh permintaan
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def sync_call_with_stream():
print("\n========== Synchronous call - Streaming text-and-image output ==========")
image_message = Message(
role="user",
content=[
{
"text": "Give me a 3-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, # Hanya pemanggilan streaming
negative_prompt="",
enable_interleave=True,
max_images=3,
size="1280*1280"
)
print("Streaming output result:")
for stream_res in image_stream_res:
print(stream_res)
if __name__ == "__main__":
sync_call_with_stream()Contoh respons
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{"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": " fried"}]}}], "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": null, "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"}}Pemanggilan asinkron
Contoh permintaan
Catatan: Pemanggilan asinkron tidak memerlukan Anda menyetel parameter stream.
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx"
# Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/zh/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def main():
"""Pemanggilan asinkron - Output teks dan gambar"""
print("========== wan2.6-image Asynchronous call - Text-and-image output ==========")
image_message = Message(
role="user",
content=[
{
"text": "Give me a 3-image tutorial for stir-fried pork with chili peppers"
}
]
)
# Buat tugas asinkron
print("---async call, creating task----")
response = ImageGeneration.async_call(
model="wan2.6-image",
api_key=api_key,
messages=[image_message],
# Pemanggilan asinkron tidak memerlukan penyetelan parameter stream
negative_prompt="",
enable_interleave=True,
max_images=3,
size="1280*1280"
)
if response.status_code == HTTPStatus.OK:
print(f"Task created successfully:")
print(response)
# Tunggu hingga tugas selesai
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"Result:")
print(status)
else:
print(f"Task failed with 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()
Contoh respons
1. Contoh respons saat membuat tugas
{
"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
}
}2. Contoh respons saat menanyakan hasil tugas
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{
"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-style favorite for many. It is known for its fresh, spicy flavor and tender meat. The preparation is simple, yet it delivers an ultimate taste experience. Today, let's learn how to make this dish together.\n\nFirst, preparing all the ingredients is the first step to success. Fresh pork, red and green chili peppers, garlic cloves, and ginger slices are essential. Slice the pork thinly, cut the peppers into sections, and slice the garlic and ginger for later use.",
"type": "text"
},
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
},
{
"text": "Next is the crucial stir-frying step. Heat the wok with cool oil, add the garlic and ginger slices to release their aroma, then add the sliced pork and stir-fry quickly until the meat changes color. After the pork is fragrant, add the cut chili peppers and continue to stir-fry to fully release their aroma, blending it perfectly with the savory meat.",
"type": "text"
},
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
},
{
"text": "Finally, add the right amount of light soy sauce, dark soy sauce, oyster sauce, and a little sugar to season. Stir-fry quickly and evenly to coat every piece of meat and pepper with the sauce. Once the sauce thickens, turn off the heat and serve. This delicious and aromatic stir-fried pork with chili peppers is now 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
}
}DashScope Java SDK
Penamaan parameter dalam SDK sebagian besar konsisten dengan HTTP API, tetapi struktur parameternya dienkapsulasi berdasarkan karakteristik bahasa pemrograman.
Karena tugas bisa memakan waktu lama, SDK mengenkapsulasi proses pemanggilan HTTP asinkron dan mendukung metode pemanggilan sinkron maupun asinkron.
Waktu spesifik yang dibutuhkan tergantung pada jumlah tugas dalam antrian dan status eksekusi layanan. Bersabarlah saat mengambil hasilnya.
Sebelum menjalankan kode berikut, pastikan versi DashScope Java SDK adalah 2.22.6 atau lebih baru.
Parameter base_url dan Kunci API berbeda untuk setiap wilayah. Contoh berikut menunjukkan cara melakukan pemanggilan di wilayah Singapura:
Singapura: https://dashscope-intl.aliyuncs.com/api/v1
Virginia: https://dashscope-us.aliyuncs.com/api/v1
Beijing: https://dashscope.aliyuncs.com/api/v1
Image editing
Pemanggilan sinkron
Contoh permintaan
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 {
// Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
// Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat 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 {
// Bangun pesan input multi-gambar
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Mendukung input multi-gambar, memungkinkan beberapa gambar referensi
Collections.singletonMap("text", "Generate an image of scrambled eggs with tomatoes using 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();
// Pengeditan gambar menggunakan pemanggilan sinkron normal. Tidak perlu menyetel stream dan enable_interleave.
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-image")
.messages(Collections.singletonList(message))
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call for image editing, 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());
}
}
}
Contoh respons
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{
"requestId": "b148327e-830f-414c-a8df-724dec28exxx",
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"total_tokens": 0,
"image_count": 1,
"size": "1280*1280"
},
"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": ""
}Pemanggilan asinkron
Contoh permintaan
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 {
// Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
// Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat 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 {
// Bangun pesan input multi-gambar
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Mendukung input multi-gambar, memungkinkan beberapa gambar referensi
Collections.singletonMap("text", "Generate an image of scrambled eggs with tomatoes using 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("1280*1280")
.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();
// Tunggu hingga tugas selesai
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());
}
}
}
Contoh respons
1. Contoh respons saat membuat tugas
{
"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
}2. Contoh respons saat menanyakan hasil tugas
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{
"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": "1280*1280",
"total_tokens": 0,
"image_count": 1
}
}Mixed text-and-image output
Pemanggilan sinkron (hanya streaming)
Contoh permintaan
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-and-image output - Streaming call example
*/
public class Main {
static {
// Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
// Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat https://www.alibabacloud.com/help/zh/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 3-image tutorial for stir-fried pork with chili peppers")
)).build();
// Output teks dan gambar harus menggunakan pemanggilan streaming
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-image")
.messages(Collections.singletonList(message))
.stream(true) // Streaming output harus diaktifkan
.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);
}
}
Contoh respons
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{"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 peppers"}]}}],"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":"pan"}]}}],"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":""}Pemanggilan asinkron
Contoh permintaan
Catatan: Pemanggilan asinkron tidak memerlukan Anda menyetel parameter stream.
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-and-image output - Asynchronous call example
*/
public class Main {
static {
// Berikut ini adalah base_url untuk wilayah Singapura. base_url berbeda-beda tergantung wilayah.
Constants.baseHttpApiUrl = "https://dashscope-intl.aliyuncs.com/api/v1";
}
// Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: apiKey="sk-xxx"
// Kunci API berbeda-beda tergantung wilayah. Untuk mendapatkan Kunci API, lihat 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", "Give me a 3-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();
// Tunggu hingga tugas selesai
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());
}
}
}
Contoh respons
1. Contoh respons saat membuat tugas
{
"requestId": "7d6c5760-334b-48c4-9b1e-08ee9c7fexxx",
"output": {
"task_id": "1bb9d9fa-bf1a-43dc-b5fe-366c1dc70xxx",
"task_status": "PENDING"
},
"status_code": 200,
"code": "",
"message": ""
}2. Contoh respons saat menanyakan hasil tugas
Tautan berlaku selama 24 jam. Anda harus segera mengunduh gambar.
{
"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-style favorite for many. It is known for its fresh, spicy flavor and tender meat. The preparation is simple, yet it delivers an ultimate taste experience. Today, let's learn how to make this dish together.\n\nFirst, preparing all the ingredients is the first step to success. Fresh pork, red and green chili peppers, garlic cloves, and ginger slices are essential. Slice the pork thinly, cut the peppers into sections, and slice the garlic and ginger for later use.",
"type": "text"
},
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
},
{
"text": "Next is to 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-15 minutes. This will make the pork 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 the wok with cool oil, add the marinated pork slices and stir-fry quickly until they change color, then set aside. Leave some oil in the wok, add the garlic and ginger slices to release their aroma, then add the chili peppers and stir-fry until fragrant. Subsequently, return the pork to the wok, add light soy sauce, dark soy sauce, a little sugar, and oyster sauce. Stir-fry quickly and evenly, and garnish with chopped green onions before serving.",
"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": ""
}Batasan
Validitas data:
task_iddanurlgambar hanya disimpan selama 24 jam. Setelah periode ini, data tersebut tidak dapat ditanyakan atau diunduh.Moderasi konten:
promptinput dan gambar output keduanya tunduk pada moderasi konten. Permintaan yang mengandung konten terlarang menghasilkan kesalahanIPInfringementSuspectatauDataInspectionFailed. Lihat kode kesalahan untuk detailnya.Konfigurasi akses jaringan: URL gambar disimpan di OSS. Jika sistem bisnis Anda tidak dapat mengakses URL OSS eksternal karena kebijakan keamanan, tambahkan nama domain OSS berikut ke daftar putih Anda.
# Daftar nama domain 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
Penagihan dan pembatasan laju
Untuk kuota gratis dan harga satuan, lihat Harga model.
Untuk batas laju model, lihat Wan.
Detail penagihan: Penagihan didasarkan pada jumlah gambar yang berhasil dihasilkan. Pemanggilan model yang gagal atau kesalahan pemrosesan tidak dikenai biaya atau tidak mengurangi kuota gratis.
Kode kesalahan
Jika pemanggilan gagal, lihat Pesan kesalahan untuk troubleshooting.
FAQ
Q: Bagaimana cara melihat biaya inferensi dan penggunaan?
A: Lihat Pertanyaan tagihan dan manajemen biaya.
Q: Mengapa contoh kode saya gagal dijalankan?
A: Anda mungkin perlu meningkatkan SDK ke versi terbaru. Untuk instruksi pembaruan, lihat Instal SDK.