All Products
Search
Document Center

Alibaba Cloud Model Studio:Wan2.6 - pembuatan dan pengeditan gambar

Last Updated:Jun 30, 2026

Wan2.6 mendukung input multi-gambar, pengeditan gambar, dan output teks-gambar interleaved.

Ikhtisar model

Model

Deskripsi

Spesifikasi gambar output

wan2.6-image

Mengedit gambar dan menghasilkan output teks-gambar interleaved.

Format gambar: PNG

Resolusi dan dimensi gambar dikonfigurasi melalui parameter size.

Catatan

Sebelum memanggil API, periksa daftar model dan harga yang didukung di setiap wilayah.

Prasyarat

Dapatkan Kunci API dan ekspor kunci API sebagai Variabel lingkungan.

Penting

Wilayah Singapura, AS (Virginia), dan Tiongkok (Beijing) memiliki Kunci API dan titik akhir permintaan yang berbeda. Keduanya tidak dapat saling dipertukarkan. Pemanggilan lintas-wilayah akan menyebabkan kegagalan otentikasi atau error layanan. Untuk informasi selengkapnya, lihat Pilih wilayah dan cakupan penerapan layanan.

HTTP sinkron

Mengembalikan hasil dalam satu permintaan. Direkomendasikan untuk sebagian besar skenario.

Singapura

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

AS (Virginia)

POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

China (Beijing)

POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Cakupan penerapan global (wilayah Frankfurt) hanya mendukung pemanggilan asinkron.

Parameter permintaan

Pengeditan gambar

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --data '{
        "model": "wan2.6-image",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "text": "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"
                        },
                        {
                            "image": "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"
                        },
                        {
                            "image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
                        }
                    ]
                }
            ]
        },
        "parameters": {
            "prompt_extend": true,
            "watermark": false,
            "n": 1,
            "enable_interleave": false,
            "size": "1K"
        }
    }'

Output teks-gambar interleaved (streaming saja)

Saat menggunakan output teks-gambar interleaved (parameters.enable_interleave = true) dengan antarmuka sinkron, streaming wajib digunakan. Tetapkan kedua kondisi berikut:

  • Tetapkan X-DashScope-SSE ke enable.

  • Tetapkan parameters.stream ke true.

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'X-DashScope-SSE: enable' \
    --data '{
        "model": "wan2.6-image",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "text": "Give me a three-image tutorial for stir-fried pork with chili peppers"
                        }
                    ]
                }
            ]
        },
        "parameters": {
            "max_images": 3,
            "size": "1280*1280",
            "stream": true,
            "enable_interleave":true
        }
    }'
Header permintaan

Content-Type string (Wajib)

Tipe konten permintaan. Harus application/json.

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

X-DashScope-SSE string (Opsional)

Mengaktifkan keluaran streaming.

  • Saat parameters.enable_interleave=true, tetapkan ke enable.

  • Dalam kasus lain, abaikan header ini.

Body permintaan

model string (Wajib)

Nama model. Tetapkan ke wan2.6-image.

input object (Wajib)

Konfigurasi input.

Properti

messages array (Wajib)

Array konten permintaan. Hanya percakapan satu putaran yang didukung — berikan satu pasangan role-content.

Properti

role string (Wajib)

Peran pesan. Tetapkan ke user.

content array (Wajib)

Array konten pesan.

Properti

text string (Wajib)

Prompt positif yang menjelaskan konten, gaya, dan komposisi gambar yang diinginkan.

Mendukung bahasa Tionghoa dan Inggris. Maksimal 2.000 karakter (setiap karakter Tionghoa, huruf, angka, atau simbol dihitung sebagai satu). Dipotong secara otomatis jika melebihi batas.

Contoh: Buat tumis tomat dan telur sesuai gaya gambar ini.

Catatan: Array content harus berisi tepat satu objek dengan bidang text.

image string (Opsional)

URL atau string gambar yang dikodekan Base64.

Batasan gambar:

  • Format gambar: JPEG, JPG, PNG (saluran alfa tidak didukung), BMP, WebP.

  • Resolusi gambar: Lebar dan tinggi masing-masing harus antara 240 hingga 8.000 piksel.

  • Ukuran file: Tidak boleh melebihi 10 MB.

Batas jumlah gambar:

  • Jumlah gambar input bergantung pada parameter parameters.enable_interleave.

    • Saat enable_interleave=true (output teks-gambar interleaved), Anda dapat menginput 0 hingga 1 gambar.

    • Saat enable_interleave=false (pengeditan gambar), Anda harus menginput 1 hingga 4 gambar.

  • Saat Anda menginput beberapa gambar, sertakan beberapa objek image dalam array content, menentukan urutan gambar berdasarkan urutan array.

Format input yang didukung:

  1. Gunakan URL yang dapat diakses publik

    • Mendukung protokol HTTP atau HTTPS.

    • Contoh: http://wanx.alicdn.com/material/xxx.jpeg.

  2. Berikan string gambar yang dikodekan Base64

    • Format: data:{MIME_type};base64,{base64_data}

    • Contoh: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (hanya ilustrasi; berikan string lengkap saat praktik)

    • Untuk panduan pengkodean Base64, lihat Metode input gambar.

parameters object (Opsional)

Parameter generasi.

Properti

negative_prompt string (opsional)

Prompt negatif yang menjelaskan hal yang tidak diinginkan dalam gambar.

Mendukung bahasa Tionghoa dan Inggris. Panjang maksimum 500 karakter. Karakter berlebih dipotong secara otomatis.

Contoh: Resolusi rendah, kualitas rendah, anggota tubuh terdistorsi, jari cacat, warna terlalu jenuh, penampilan seperti lilin, tanpa detail wajah, permukaan terlalu halus, tampilan hasil AI. Komposisi kacau. Teks buram atau terdistorsi.

size string (Opsional)

Resolusi gambar output. Mendukung dua metode: merujuk proporsi gambar input atau langsung menentukan dimensi.

Saat enable_interleave=false (mode pengeditan gambar):

  • Metode 1: Merujuk proporsi gambar input (direkomendasikan)

    Opsi resolusi output yang tersedia: 1K (default), 2K.

    • 1K: Total piksel output mendekati 1.280×1.280, mempertahankan rasio aspek gambar input terakhir.

    • 2K: Total piksel output mendekati 2.048×2.048, mempertahankan rasio aspek gambar input terakhir.

  • Metode 2: Tentukan lebar dan tinggi gambar output dalam piksel

    Total piksel harus berada di antara [768×768, 2.048×2.048], dengan rentang rasio aspek [1:4, 4:1].

    Nilai piksel output aktual adalah kelipatan 16 terdekat dari nilai yang ditentukan.

Saat enable_interleave=true (mode output teks-gambar interleaved):

  • Metode 1: Merujuk proporsi gambar input (metode default)

    • Jika total piksel gambar input ≤ 1.280×1.280, output sesuai dengan total piksel dan rasio aspek input.

    • Jika total piksel gambar input > 1.280×1.280, total piksel output mendekati 1.280×1.280, mempertahankan rasio aspek input.

    • Jika tidak ada gambar input yang diberikan, ukuran output adalah 1.280×1.280.

  • Metode 2: Tentukan lebar dan tinggi gambar output dalam piksel

    Total piksel harus berada di antara [768×768, 1.280×1.280], dengan rentang rasio aspek [1:4, 4:1].

    Nilai piksel output aktual adalah kelipatan 16 terdekat dari nilai yang ditentukan.

Resolusi yang direkomendasikan untuk rasio aspek umum

  • 1:1: 1.280×1.280

  • 2:3: 800*1200

  • 3:2: 1.200×800

  • 3:4: 960×1280

  • 4:3: 1.280×960

  • 9:16: 720×1280

  • 16:9: 1.280×720

  • 21:9: 1.344×576

enable_interleave bool (Opsional)

Mengontrol mode generasi gambar:

  • false (default): Menunjukkan mode pengeditan gambar (mendukung input multi-gambar dan generasi konsistensi subjek).

    • Kasus penggunaan: Edit, terapkan style transfer, atau hasilkan gambar konsisten-subjek berdasarkan 1 hingga 4 gambar input.

    • Input: Harus menyediakan minimal satu gambar referensi.

    • Output: Dapat menghasilkan 1 hingga 4 gambar hasil.

  • true: Mengaktifkan mode output teks-gambar interleaved (mendukung input satu gambar atau tanpa gambar).

    • Kasus penggunaan: Hasilkan konten yang menggabungkan teks dan gambar berdasarkan deskripsi teks, atau lakukan generasi teks-ke-gambar murni.

    • Input: Dapat memberikan tanpa gambar (teks-ke-gambar) atau hingga satu gambar referensi.

    • Output: Menghasilkan konten campuran yang berisi teks dan gambar.

n integer (Opsional)

Penting

Parameter ini memengaruhi biaya (dikenakan per gambar berhasil — lihat harga).

Jumlah gambar yang akan dihasilkan. Perilaku bergantung pada enable_interleave:

  • Saat enable_interleave=false (mode pengeditan gambar):

    • Secara langsung mengontrol jumlah gambar yang dihasilkan.

    • Rentang: 1 hingga 4. Nilai default adalah 4.

    • Saat pengujian, tetapkan nilai ini ke 1 untuk validasi berbiaya rendah.

  • Saat enable_interleave=true (mode teks-gambar interleaved):

    • Default ke 1 dan harus tetap 1. Nilai lain menyebabkan error.

    • Gunakan max_images untuk mengontrol jumlah gambar dalam mode ini.

max_images integer (Opsional)

Penting

Parameter ini memengaruhi biaya (dikenakan per gambar berhasil — lihat harga).

Hanya efektif dalam mode teks-gambar interleaved (enable_interleave=true).

  • Jumlah maksimum gambar yang dihasilkan model dalam satu respons.

  • Rentang: 1 hingga 5. Nilai default adalah 5.

  • Menetapkan batas atas. Model mungkin menghasilkan lebih sedikit gambar daripada yang diminta.

prompt_extend bool (Opsional)

Hanya efektif dalam mode pengeditan gambar (enable_interleave = false).

Mengaktifkan penulisan ulang prompt cerdas. Hanya mengoptimalkan prompt positif; prompt negatif tetap tidak berubah.

  • true (default)

  • false

stream bool (Opsional)

Mengaktifkan keluaran streaming. Wajib (tetapkan ke true) saat enable_interleave=true.

  • false (default)

  • true

watermark bool (Opsional)

Menambahkan label watermark di pojok kanan bawah gambar dengan teks tetap "AI Generated".

  • false (default)

  • true

seed integer (opsional)

Bibit angka acak. Rentang valid: [0,2147483647].

Menggunakan seed yang sama menghasilkan output serupa. Jika diabaikan, algoritma menggunakan seed acak.

Catatan: Generasi gambar bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya mungkin berbeda.

Parameter respons

Eksekusi tugas berhasil

Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan.

{
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "content": [
                        {
                            "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ],
                    "role": "assistant"
                }
            }
        ],
        "finished": true
    },
    "usage": {
        "image_count": 1,
        "input_tokens": 0,
        "output_tokens": 0,
        "size": "1376*768",
        "total_tokens": 0
    },
    "request_id": "a3f4befe-cacd-49c9-8298-xxxxxx"
}

Eksekusi tugas berhasil (keluaran streaming)

Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan.

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

Kegagalan eksekusi tugas

Jika Tugas gagal, informasi kesalahan akan dikembalikan. Gunakan bidang code dan message untuk mengidentifikasi penyebabnya. Lihat 错误码 untuk pemecahan masalah.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Output tugas.

Properti

choices array of object

Konten output yang dihasilkan model.

Properti

finish_reason string

Alasan penghentian tugas.

Skenario output non-streaming: Berhenti secara alami dengan stop.

Skenario output streaming: Parameter ini menunjukkan apakah aliran data telah selesai ditransmisikan.

  • Selama transmisi: Paket data sebelumnya terus-menerus mengembalikan "finish_reason": "null", menunjukkan konten masih dihasilkan. Lanjutkan menerima.

  • Pada akhir transmisi: Hanya struktur JSON terakhir yang mengembalikan "finish_reason":"stop", menunjukkan permintaan streaming telah sepenuhnya selesai. Hentikan penerimaan.

message object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pesan, tetap sebagai assistant.

content array

Properti

type string

Tipe output. Nilai enumerasi: text, image.

text string

Teks yang dihasilkan.

image string

URL gambar yang dihasilkan dalam format PNG.

Tautan kedaluwarsa setelah 24 jam. Unduh dan simpan gambar segera.

finished bool

Flag penyelesaian permintaan.

  • true

  • false

usage object

Statistik output. Hanya menghitung hasil yang berhasil.

Properti

image_count integer

Jumlah gambar yang dihasilkan.

size string

Resolusi gambar yang dihasilkan. Contoh: 1376*768.

input_tokens integer

Ditagih per jumlah gambar.

  • Dalam mode pengeditan gambar, tetap 0.

  • Dalam mode teks-gambar interleaved, bidang ini menghitung token teks input (tidak ditagih).

output_tokens integer

Ditagih per jumlah gambar.

  • Dalam mode pengeditan gambar, tetap 0.

  • Dalam mode teks-gambar interleaved, bidang ini menghitung token teks output (tidak ditagih).

total_tokens integer

Ditagih per jumlah gambar.

  • Dalam mode pengeditan gambar, tetap 0.

  • Dalam mode teks-gambar interleaved, bidang ini menghitung total token (tidak ditagih).

request_id string

Identifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan kesalahan rinci, hanya dikembalikan untuk permintaan yang gagal. Lihat Kode kesalahan.

HTTP asinkron

Proses: Buat tugas → Poll hasil

Langkah 1: Buat tugas dan dapatkan ID tugas

Singapura

POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

AS (Virginia)

POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation

China (Beijing)

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Jerman (Frankfurt)

POST https://<u><u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u></u>/api/v1/services/aigc/image-generation/generation

Saat melakukan panggilan, ganti WorkspaceId dengan ID Ruang Kerja Anda.

Catatan
  • Setelah tugas dibuat, gunakan task_id yang dikembalikan untuk menanyakan hasilnya. task_id berlaku selama 24 jam. Jangan membuat tugas duplikat. Sebagai gantinya, gunakan polling untuk mengambil hasilnya.

  • Untuk panduan pemula, lihat Panggil API dengan Postman atau cURL.

Parameter permintaan

Pengeditan gambar

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'X-DashScope-Async: enable' \
    --data '{
        "model": "wan2.6-image",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "text": "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"
                        },
                        {
                            "image": "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"
                        },
                        {
                            "image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
                        }
                    ]
                }
            ]
        },
        "parameters": {
            "prompt_extend": true,
            "watermark": false,
            "n": 1,
            "enable_interleave": false,
            "size": "1K"
        }
    }'

Output teks-gambar interleaved

curl --location 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation' \
    --header 'Content-Type: application/json' \
    --header "Authorization: Bearer $DASHSCOPE_API_KEY" \
    --header 'X-DashScope-Async: enable' \
    --data '{
        "model": "wan2.6-image",
        "input": {
            "messages": [
                {
                    "role": "user",
                    "content": [
                        {
                            "text": "Give me a three-image tutorial for stir-fried pork with chili peppers"
                        }
                    ]
                }
            ]
        },
        "parameters": {
            "max_images": 3,
            "size": "1280*1280",
            "enable_interleave":true
        }
    }'

Header permintaan

Content-Type string (Wajib)

Tipe konten permintaan. Harus application/json.

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

X-DashScope-Async string (Wajib)

Sakelar mode asinkron. Harus ditetapkan ke enable.

Penting

Mengabaikan header ini mengembalikan error: “current user api does not support synchronous calls”.

Body permintaan

model string (Wajib)

Nama model.

Contoh: wan2.6-image

input object (Wajib)

Konfigurasi input.

Properti

messages array (Wajib)

Array konten permintaan. Hanya percakapan satu putaran yang didukung — berikan satu pasangan role-content. Percakapan multi-putaran tidak didukung.

Properti

role string (Wajib)

Peran pesan. Tetapkan ke user.

content array (Wajib)

Array konten pesan.

Properti

text string (Wajib)

Prompt positif yang menjelaskan konten, gaya, dan komposisi gambar yang diinginkan.

Mendukung bahasa Tionghoa dan Inggris. Maksimal 2.000 karakter (setiap karakter Tionghoa, huruf, angka, atau simbol dihitung sebagai satu). Dipotong secara otomatis jika melebihi batas.

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

Catatan: Array content harus berisi tepat satu objek dengan bidang text.

image string (Opsional)

URL atau string gambar yang dikodekan Base64.

Batasan gambar:

  • Format gambar: JPEG, JPG, PNG (saluran alfa tidak didukung), BMP, WebP.

  • Resolusi gambar: Lebar dan tinggi masing-masing harus antara 240 hingga 8.000 piksel.

  • Ukuran file: Tidak boleh melebihi 10 MB.

Batas jumlah gambar:

  • Jumlah gambar input bergantung pada parameter parameters.enable_interleave.

    • Saat enable_interleave=true (output teks-gambar interleaved), Anda dapat menginput 0 hingga 1 gambar.

    • Saat enable_interleave=false (pengeditan gambar), Anda harus menginput 1 hingga 4 gambar.

  • Saat Anda menginput beberapa gambar, sertakan beberapa objek image dalam array content, menentukan urutan gambar berdasarkan urutan array.

Format input yang didukung:

  1. Gunakan URL yang dapat diakses publik

    • Mendukung protokol HTTP atau HTTPS.

    • Contoh: http://wanx.alicdn.com/material/xxx.jpeg.

  2. Berikan string gambar yang dikodekan Base64

    • Format: data:{MIME_type};base64,{base64_data}

    • Contoh: data:image/jpeg;base64,GDU7MtCZzEbTbmRZ... (hanya ilustrasi; berikan string lengkap saat praktik)

    • Untuk panduan pengkodean Base64, lihat Metode input gambar.

parameters object (Opsional)

Parameter generasi.

Properti

negative_prompt string (opsional)

Prompt negatif yang menjelaskan hal yang tidak diinginkan dalam gambar.

Mendukung bahasa Tionghoa dan Inggris. Panjang maksimum 500 karakter. Karakter berlebih dipotong secara otomatis.

Contoh: Resolusi rendah, kualitas rendah, anggota tubuh terdistorsi, jari cacat, warna terlalu jenuh, penampilan seperti lilin, tanpa detail wajah, permukaan terlalu halus, tampilan hasil AI. Komposisi kacau. Teks buram atau terdistorsi.

size string (Opsional)

Resolusi gambar output. Mendukung dua metode: merujuk proporsi gambar input atau langsung menentukan dimensi.

Saat enable_interleave=false (mode pengeditan gambar):

  • Metode 1: Merujuk proporsi gambar input (direkomendasikan)

    Opsi resolusi output yang tersedia: 1K (default), 2K.

    • 1K: Total piksel output mendekati 1280*1280, mempertahankan rasio aspek gambar input terakhir.

    • 2K: Total piksel output mendekati 2048*2048, mempertahankan rasio aspek gambar input terakhir.

  • Metode 2: Tentukan lebar dan tinggi gambar output dalam piksel

    Total piksel harus berada di antara [768768, 20482048], dengan rentang rasio aspek [1:4, 4:1].

    Nilai piksel output aktual adalah kelipatan 16 terdekat dari nilai yang ditentukan.

Saat enable_interleave=true (mode output teks-gambar interleaved):

  • Metode 1: Merujuk proporsi gambar input (metode default)

    • Jika total piksel gambar input ≤ 1280*1280, output sesuai dengan total piksel dan rasio aspek input.

    • Jika total piksel gambar input > 12801280, total piksel output mendekati 12801280, mempertahankan rasio aspek input.

    • Jika tidak ada gambar input yang diberikan, ukuran output adalah 1280*1280.

  • Metode 2: Tentukan lebar dan tinggi gambar output dalam piksel

    Total piksel harus berada di antara [768768, 12801280], dengan rentang rasio aspek [1:4, 4:1].

    Nilai piksel output aktual adalah kelipatan 16 terdekat dari nilai yang ditentukan.

Resolusi yang direkomendasikan untuk rasio aspek umum

  • 1:1: 1280*1280

  • 2:3: 800*1200

  • 3:2: 1200*800

  • 3:4: 960*1280

  • 4:3: 1280*960

  • 9:16: 720*1280

  • 16:9: 1280*720

  • 21:9: 1344*576

enable_interleave bool (Opsional)

Mengontrol mode generasi gambar:

  • false (default): Menunjukkan mode pengeditan gambar (mendukung input multi-gambar dan generasi konsistensi subjek).

    • Kasus penggunaan: Edit, terapkan style transfer, atau hasilkan gambar konsisten-subjek berdasarkan 1 hingga 4 gambar input.

    • Input: Harus menyediakan minimal satu gambar referensi.

    • Output: Dapat menghasilkan 1 hingga 4 gambar hasil.

  • true: Mengaktifkan mode output teks-gambar interleaved (mendukung input satu gambar atau tanpa gambar).

    • Kasus penggunaan: Hasilkan konten yang menggabungkan teks dan gambar berdasarkan deskripsi teks, atau lakukan generasi teks-ke-gambar murni.

    • Input: Dapat memberikan tanpa gambar (teks-ke-gambar) atau hingga satu gambar referensi.

    • Output: Menghasilkan konten campuran yang berisi teks dan gambar.

n integer (Opsional)

Penting

Parameter ini memengaruhi biaya (dikenakan per gambar berhasil — lihat harga).

Jumlah gambar yang akan dihasilkan. Perilaku bergantung pada enable_interleave:

  • Saat enable_interleave=false (mode pengeditan gambar):

    • Secara langsung mengontrol jumlah gambar yang dihasilkan.

    • Rentang: 1 hingga 4. Nilai default adalah 4.

    • Saat pengujian, tetapkan nilai ini ke 1 untuk validasi berbiaya rendah.

  • Saat enable_interleave=true (mode teks-gambar interleaved):

    • Default ke 1 dan harus tetap 1. Nilai lain menyebabkan error.

    • Gunakan max_images untuk mengontrol jumlah gambar dalam mode ini.

max_images integer (Opsional)

Penting

Parameter ini memengaruhi biaya (dikenakan per gambar berhasil — lihat harga).

Hanya efektif dalam mode teks-gambar interleaved (enable_interleave=true).

  • Jumlah maksimum gambar yang dihasilkan model dalam satu respons.

  • Rentang: 1 hingga 5. Nilai default adalah 5.

  • Menetapkan batas atas. Model mungkin menghasilkan lebih sedikit gambar daripada yang diminta.

prompt_extend bool (Opsional)

Hanya efektif dalam mode pengeditan gambar (enable_interleave = false).

Mengaktifkan penulisan ulang prompt cerdas. Hanya mengoptimalkan prompt positif; prompt negatif tetap tidak berubah.

  • true (default)

  • false

watermark bool (Opsional)

Menambahkan label watermark di pojok kanan bawah gambar dengan teks tetap "AI Generated".

  • false (default)

  • true

seed integer (opsional)

Bibit angka acak. Rentang valid: [0,2147483647].

Menggunakan seed yang sama menghasilkan output serupa. Jika diabaikan, algoritma menggunakan seed acak.

Catatan: Generasi gambar bersifat probabilistik. Bahkan dengan seed yang sama, hasilnya mungkin berbeda.

Parameter respons

Respons berhasil

Simpan task_id untuk menanyakan status dan hasil tugas.

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

Respons error

Pembuatan tugas gagal. Lihat kode galat.

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

output object

Output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

request_id string

Identifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan error detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码.

Langkah 2: Tanyakan hasil menggunakan ID tugas

Singapura

GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

AS (Virginia)

GET https://dashscope-us.aliyuncs.com/api/v1/tasks/{task_id}

China (Beijing)

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

Saat memanggil, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Jerman (Frankfurt)

GET https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1/tasks/{task_id}

Saat melakukan panggilan, ganti {WorkspaceId} dengan ID Ruang Kerja Anda yang sebenarnya.

Catatan
  • Rekomendasi polling: Generasi gambar memakan waktu. Gunakan mekanisme polling dengan interval yang masuk akal, misalnya 10 detik.

  • Transisi status tugas: PENDING → RUNNING → SUCCEEDED atau FAILED.

  • Tautan hasil: Setelah tugas berhasil, URL gambar yang berlaku selama 24 jam dikembalikan. Unduh dan simpan gambar ke penyimpanan permanen, seperti OSS.

Parameter permintaan

Tanyakan hasil tugas

Ganti {task_id} dengan nilai task_id yang dikembalikan oleh panggilan API sebelumnya. task_id berlaku untuk kueri selama 24 jam.

curl -X GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id} \
--header "Authorization: Bearer $DASHSCOPE_API_KEY"
Header permintaan

Authorization string (Wajib)

Mengotentikasi permintaan dengan Kunci API Model Studio. Contoh: Bearer sk-xxxx.

Parameter path URL

task_id string (Wajib)

ID tugas.

Parameter respons

Eksekusi tugas berhasil

Data tugas (status tugas dan URL gambar) hanya disimpan selama 24 jam lalu secara otomatis dihapus. Segera simpan gambar yang dihasilkan.

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

Kegagalan eksekusi tugas

Jika tugas gagal, informasi error dikembalikan. Gunakan bidang code dan message untuk mengidentifikasi penyebabnya. Lihat 错误码 untuk troubleshooting.

{
    "request_id": "a4d78a5f-655f-9639-8437-xxxxxx",
    "code": "InvalidParameter",
    "message": "num_images_per_prompt must be 1"
}

output object

Informasi output tugas.

Properti

task_id string

ID tugas. Berlaku untuk kueri selama 24 jam.

task_status string

Status tugas.

Nilai enumerasi

  • PENDING

  • RUNNING

  • SUCCEEDED

  • FAILED

  • CANCELED

  • UNKNOWN: Tugas tidak ada atau statusnya tidak diketahui.

Transisi status selama polling:

  • PENDING → RUNNING → SUCCEEDED atau FAILED.

  • Status kueri awal biasanya PENDING atau RUNNING.

  • Saat status berubah menjadi SUCCEEDED, respons berisi URL gambar yang dihasilkan.

  • Jika statusnya FAILED, periksa pesan error dan coba ulang tugas tersebut.

submit_time string

Waktu saat tugas diajukan. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

scheduled_time string

Waktu saat tugas dieksekusi. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

end_time string

Waktu saat tugas selesai. Waktu dalam UTC+8 dan formatnya YYYY-MM-DD HH:mm:ss.SSS.

finished bool

Flag penyelesaian permintaan.

  • true

  • false

choices array of object

Konten output yang dihasilkan model.

Properti

finish_reason string

Alasan penghentian tugas. Berhenti secara alami dengan stop.

message object

Pesan yang dikembalikan oleh model.

Properti

role string

Peran pesan, tetap sebagai assistant.

content array

Properti

type string

Tipe output. Nilai enumerasi: text, image.

text string

Teks yang dihasilkan.

image string

URL gambar yang dihasilkan dalam format PNG.

Tautan kedaluwarsa setelah 24 jam. Unduh dan simpan gambar segera.

usage object

Statistik output. Hanya menghitung hasil yang berhasil.

Properti

image_count integer

Jumlah gambar yang dihasilkan.

size string

Resolusi gambar yang dihasilkan. Contoh: 1376*768.

input_tokens integer

Jumlah token input. Ditagih per jumlah gambar. Saat ini tetap 0.

output_tokens integer

Jumlah token output. Ditagih per jumlah gambar. Saat ini tetap 0.

total_tokens integer

Jumlah total token. Ditagih per jumlah gambar. Saat ini tetap 0.

request_id string

Identifikasi permintaan unik untuk pelacakan dan troubleshooting.

code string

Kode error. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码.

message string

Pesan error detail. Hanya dikembalikan untuk permintaan yang gagal. Lihat 错误码.

DashScope Python SDK

Parameter SDK sejalan dengan antarmuka HTTP, disesuaikan sesuai konvensi bahasa.

SDK menangani pemanggilan asinkron secara internal dan mendukung pemanggilan sinkron maupun asinkron.

Durasi aktual bervariasi tergantung panjang antrian dan beban layanan.
Penting

Membutuhkan DashScope Python SDK versi 1.25.8 atau lebih baru. Instal SDK.

Parameter base_url dan Kunci API bersifat spesifik wilayah. Contoh panggilan dari wilayah Singapura:

Singapura

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

AS (Virginia)

https://dashscope-us.aliyuncs.com/api/v1

China (Beijing)

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

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Jerman (Frankfurt)

https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1

Ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Cakupan penerapan global (wilayah Frankfurt) hanya mendukung pemanggilan asinkron.

Pengeditan gambar

Sinkron

Contoh permintaan
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# base_url wilayah Singapura. Base URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

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

print(rsp)
Contoh respons
URL kedaluwarsa setelah 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": "1376*768",
        "total_tokens": 0
    }
}

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

# base_url wilayah Singapura. Base URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/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 a tomato and egg stir-fry based on the style of image 1 and the background of image 2'},
            {'image': 'https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png'},
            {'image': 'https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp'}
        ]
    )
    response = ImageGeneration.async_call(
        model="wan2.6-image",
        api_key=api_key,
        messages=[message],
        negative_prompt="",
        prompt_extend=True,
        watermark=False,
        n=1,
        enable_interleave=False,
        size="1K"
    )
    
    if response.status_code == 200:
        print("Task created successfully:", response)
        return response  # 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 info tugas asinkron
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 pembuatan 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
        }
    }
  1. Contoh respons kueri hasil tugas

    URL kedaluwarsa setelah 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": "1376*768",
            "total_tokens": 0,
            "image_count": 1
        }
    }

Output teks-gambar interleaved

Sinkron (streaming saja)

Contoh permintaan
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message

# URL wilayah Singapura. Base URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

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

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

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

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

if __name__ == "__main__":
    sync_call_with_stream()
Contoh respons
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Chili"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 0, "characters": 0, "total_tokens": 28, "image_count": 0, "size": "0*0"}}
{"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Stir-fry"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 1, "characters": 0, "total_tokens": 29, "image_count": 0, "size": "0*0"}}
{"status_code": 200, "request_id": "5b98e8f3-aeff-4c20-a26c-499a7525axxx", "code": "", "message": "", "output": {"text": null, "finish_reason": null, "choices": [{"finish_reason": "null", "message": {"role": "assistant", "content": [{"type": "text", "text": "Pork"}]}}], "audio": null, "finished": false}, "usage": {"input_tokens": 28, "output_tokens": 2, "characters": 0, "total_tokens": 30, "image_count": 0, "size": "0*0"}}

......

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

Asinkron

Contoh permintaan

Catatan: Pemanggilan asinkron tidak memerlukan 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

# URL wilayah Singapura. Base URL berbeda tiap wilayah.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'

# Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: api_key="sk-xxx"
# Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")

def main():
    """Pemanggilan asinkron - Output teks-gambar"""
    print("========== wan2.6-image Asynchronous call - Text-image output ==========")

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

    # 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 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"Results:")
            print(status)
        else:
            print(f"Task failed, status: {status.output.task_status}")
    else:
        print(f"Task creation failed: {response.code} - {response.message}")

if __name__ == "__main__":
    try:
        main()
    except Exception as e:
        print(f"Execution error: {str(e)}")
        import traceback
        traceback.print_exc()
Contoh respons
  1. Contoh respons pembuatan 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
        }
    }
  1. Contoh respons kueri hasil tugas

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

DashScope Java SDK

Parameter SDK sejalan dengan antarmuka HTTP, dikemas sesuai konvensi bahasa.

SDK menangani pemanggilan asinkron secara internal dan mendukung pemanggilan sinkron maupun asinkron.

Durasi aktual tergantung panjang antrian dan beban layanan.
Penting

Membutuhkan DashScope Java SDK versi 2.22.6 atau lebih baru.

Parameter base_url dan Kunci API tidak dapat saling dipertukarkan antar wilayah. Contoh untuk wilayah Singapura:

Singapura

https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

AS (Virginia)

https://dashscope-us.aliyuncs.com/api/v1

China (Beijing)

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

Saat melakukan panggilan, ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Jerman (Frankfurt)

https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1

Ganti WorkspaceId dengan ID ruang kerja Anda yang sebenarnya.

Cakupan penerapan global (wilayah Frankfurt) hanya mendukung pemanggilan asinkron.

Pengeditan gambar

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 Pengeditan gambar - Contoh pemanggilan sinkron
 */
public class Main {

    static {
        // URL wilayah Singapura. Base URL berbeda tiap wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey="sk-xxx"
    // Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/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; berikan beberapa gambar referensi
                        Collections.singletonMap("text", "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"),
                        Collections.singletonMap("image", "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"),
                        Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp")
                )).build();

        // Pengeditan gambar menggunakan pemanggilan sinkron standar; tidak perlu mengatur stream atau enable_interleave
        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.6-image")
                .messages(Collections.singletonList(message))
                .n(1)
                .size("1K")
                .negativePrompt("")
                .promptExtend(true)
                .build();

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

    public static void main(String[] args) {
        try {
            basicCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
    }
}
Contoh respons
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{
    "requestId": "b148327e-830f-414c-a8df-724dec28exxx",
    "usage": {
        "input_tokens": 0,
        "output_tokens": 0,
        "total_tokens": 0,
        "image_count": 1,
        "size": "1376*768"
    },
    "output": {
        "choices": [
            {
                "finish_reason": "stop",
                "message": {
                    "role": "assistant",
                    "content": [
                        {
                            "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
                            "type": "image"
                        }
                    ]
                }
            }
        ],
        "finished": true
    },
    "status_code": 200,
    "code": "",
    "message": ""
}

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 Pengeditan gambar - Contoh pemanggilan asinkron
 */
public class Main {

    static {
        // URL wilayah Singapura. Base URL berbeda tiap wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey="sk-xxx"
    // Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/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; berikan beberapa gambar referensi
                        Collections.singletonMap("text", "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"),
                        Collections.singletonMap("image", "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"),
                        Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp")
                )).build();

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

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

        String taskId = result.getOutput().getTaskId();
        // 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 pembuatan 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
    }
  1. Contoh respons kueri hasil tugas

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

Output teks-gambar interleaved

Pemanggilan sinkron (streaming saja)

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 Output teks-gambar - Contoh pemanggilan streaming
 */
public class Main {

    static {
        // URL wilayah Singapura. Base URL berbeda tiap wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey="sk-xxx"
    // Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

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

        // Output teks-gambar memerlukan pemanggilan streaming
        ImageGenerationParam param = ImageGenerationParam.builder()
                .apiKey(apiKey)
                .model("wan2.6-image")
                .messages(Collections.singletonList(message))
                .stream(true) // Harus mengaktifkan keluaran streaming
                .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
URL kedaluwarsa setelah 24 jam. Unduh gambar segera.
{"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":0,"total_tokens":28,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"Chili"}]}}],"finished":false},"status_code":200,"code":"","message":""}
{"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":1,"total_tokens":29,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"stir-fry"}]}}],"finished":false},"status_code":200,"code":"","message":""}
{"requestId":"12c7432c-8028-4289-a97c-4e22df98bxxx","usage":{"input_tokens":28,"output_tokens":2,"total_tokens":30,"image_count":0,"size":"0*0"},"output":{"choices":[{"finish_reason":"null","message":{"role":"assistant","content":[{"type":"text","text":"pork"}]}}],"finished":false},"status_code":200,"code":"","message":""}

......

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

......

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

......

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

Pemanggilan asinkron

Contoh permintaan

Catatan: Pemanggilan asinkron tidak memerlukan 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 Output teks-gambar - Contoh pemanggilan asinkron
 */
public class Main {

    static {
        // URL wilayah Singapura. Base URL berbeda tiap wilayah.
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }

    // Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan: apiKey="sk-xxx"
    // Kunci API berbeda tiap wilayah. Dapatkan Kunci API: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    static String apiKey = System.getenv("DASHSCOPE_API_KEY");

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

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

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

        String taskId = result.getOutput().getTaskId();
        // 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 pembuatan tugas

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

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

Batasan

  • Validitas data: task_id dan url gambar hanya disimpan selama 24 jam. Setelah periode ini, data tersebut tidak dapat diakses atau diunduh.

  • Moderasi konten: Baik prompt input maupun gambar output menjalani moderasi konten. Konten yang tidak sesuai mengembalikan error IPInfringementSuspect atau DataInspectionFailed. Lihat 错误码.

Penagihan dan pembatasan laju

  • Kuota gratis dan harga: Harga model.

  • Untuk batas laju model, lihat Wanxiang.

  • Anda dikenai biaya per gambar yang berhasil dihasilkan. Pemanggilan yang gagal tidak dikenai biaya dan tidak mengurangi kuota gratis.

Kode error

Jika pemanggilan model gagal dan mengembalikan pesan error, lihat 错误码 untuk penyelesaian.

FAQ

T: Bagaimana cara melihat biaya inferensi dan volume pemanggilan model?

J: Lihat Penyelidikan tagihan dan manajemen biaya.

T: Mengapa saya tidak bisa menjalankan contoh kode?

J: Tingkatkan SDK Anda ke versi terbaru. Instal SDK.