O Wan2.6 oferece suporte a entrada de múltiplas imagens, edição de imagens e saída intercalada de texto e imagem.
Visão geral do modelo
|
Modelo |
Descrição |
Especificações da imagem de saída |
|
wan2.6-image |
Edita imagens e gera saída intercalada de texto e imagem. |
Formato da imagem: PNG A resolução e as dimensões da imagem são configuradas por meio do parâmetro size. |
Antes de chamar a API, verifique a lista de modelos e preços compatíveis em cada região.
Pré-requisitos
Obtenha uma chave de API e exporte a chave de API como uma variável de ambiente.
As regiões Singapore, US (Virginia) e China (Beijing) possuem chaves de API e endpoints de solicitação separados. Eles não podem ser usados de forma intercambiável. Chamadas entre regiões resultam em falhas de autenticação ou erros de service. Para mais informações, consulte Selecione uma região e escopo de implantação do service.
HTTP síncrono
Retorna resultados em uma única solicitação. Recomendado para a maioria dos cenários.
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
US (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
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
O escopo de implantação global (região de Frankfurt) suporta apenas chamadas assíncronas .
Parâmetros da solicitação |
Edição de imagem
Saída intercalada de texto e imagem (apenas streaming)Ao usar a saída intercalada de texto e imagem (
|
Cabeçalhos da solicitação |
|
|
Content-Type O tipo de conteúdo da solicitação. Deve ser |
|
|
Authorization Autentica a solicitação com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. |
|
|
X-DashScope-SSE Ativa a saída em streaming.
|
|
Corpo da solicitação |
|
|
model Nome do modelo. Defina como wan2.6-image. |
|
|
input Configuração de entrada. |
|
|
parameters Parâmetros de geração. |
Parâmetros da resposta |
Execução bem-sucedida da tarefaOs dados da tarefa (status da tarefa e URLs das imagens) são retidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas prontamente.
Execução bem-sucedida da tarefa (saída em streaming)Os dados da tarefa (status da tarefa e URLs das imagens) são retidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas prontamente.
Falha na execução da tarefaSe a tarefa falhar, informações de erro serão retornadas. Use os campos code e message para identificar a causa. Consulte Códigos de erro para solução de problemas.
|
|
output Saída da tarefa. |
|
|
usage Estatísticas de saída. Conta apenas resultados bem-sucedidos. |
|
|
request_id Identificador único da solicitação para rastreamento e solução de problemas. |
|
|
code Código de erro. Retornado apenas para solicitações com falha. Consulte Códigos de erro. |
|
|
message Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro. |
HTTP assíncrono
Fluxo: Criar tarefa → Consultar resultados
Etapa 1: Criar a tarefa e obter o ID da tarefa
Singapore
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
US (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
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Germany (Frankfurt)
POST https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1/services/aigc/image-generation/generation
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do Workspace.
Após criar a tarefa, utilize o
task_idretornado para consultar o resultado. Otask_idpermanece válido por 24 horas. Não crie tarefas duplicadas. Em vez disso, use consultas periódicas (polling) para recuperar o resultado.Para orientações destinadas a iniciantes, consulte Chamar APIs com Postman ou cURL.
Parâmetros da requisição |
Edição de imagem
Saída intercalada de texto e imagem
|
Cabeçalhos da requisição |
|
|
Content-Type Tipo de conteúdo da requisição. Deve ser |
|
|
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. |
|
|
X-DashScope-Async Alternador do modo assíncrono. Deve ser definido como Importante
A omissão deste cabeçalho retorna o erro: “current user api does not support synchronous calls”. |
|
Corpo da requisição |
|
|
model Nome do modelo. Exemplo: wan2.6-image |
|
|
input Configuração de entrada. |
|
|
parameters Parâmetros de geração. |
Parâmetros da resposta |
Resposta bem-sucedidaSalve o
Resposta de erroFalha na criação da tarefa. Consulte Códigos de erro.
|
|
output Saída da tarefa. |
|
|
request_id Identificador único da requisição para rastreamento e solução de problemas. |
|
|
code Código de erro. Retornado apenas para requisições com falha. Consulte Códigos de erro. |
|
|
message Mensagem de erro detalhada. Retornada apenas para requisições com falha. Consulte Códigos de erro. |
Etapa 2: Consultar resultados usando o ID da tarefa
Singapore
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
US (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}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do workspace real.
Germany (Frankfurt)
GET https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
Ao fazer a chamada, substitua {WorkspaceId} pelo seu ID do Workspace real.
Recomendação de polling: A geração de imagens leva tempo. Utilize um mecanismo de consulta periódica com um intervalo razoável, como 10 segundos.
Transição de estado da tarefa: PENDING → RUNNING → SUCCEEDED ou FAILED.
Link do resultado: Após o sucesso da tarefa, uma URL de imagem válida por 24 horas é retornada. Baixe e salve a imagem em um armazenamento permanente, como o OSS.
Parâmetros da requisição |
Consultar resultados da tarefaSubstitua |
Cabeçalhos da requisição |
|
|
Authorization Autentica a requisição com uma chave de API do Model Studio. Exemplo: Bearer sk-xxxx. |
|
Parâmetros de caminho da URL |
|
|
task_id O ID da tarefa. |
Parâmetros de resposta |
Execução bem-sucedida da tarefaOs dados da tarefa (status e URLs das imagens) são retidos por apenas 24 horas e depois removidos automaticamente. Salve as imagens geradas imediatamente.
Falha na execução da tarefaSe a tarefa falhar, informações de erro serão retornadas. Utilize os campos code e message para identificar a causa. Consulte Códigos de erro para solução de problemas.
|
|
output Informações de saída da tarefa. |
|
|
usage Estatísticas de saída. Conta apenas resultados bem-sucedidos. |
|
|
request_id Identificador único da solicitação para rastreamento e solução de problemas. |
|
|
code Código de erro. Retornado apenas para solicitações com falha. Consulte Códigos de erro. |
|
|
message Mensagem de erro detalhada. Retornada apenas para solicitações com falha. Consulte Códigos de erro. |
DashScope Python SDK
Os parâmetros do SDK estão alinhados com a interface HTTP, adaptados às convenções de cada linguagem.
O SDK gerencia chamadas assíncronas internamente e suporta invocação síncrona e assíncrona.
A duração real varia conforme o tamanho da fila e a carga do service.
Requer DashScope Python SDK versão 1.25.8 ou posterior. Instalar SDK.
O base_url e a chave de API são específicos por região. Exemplo de chamada na região de Singapore:
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao realizar a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
US (Virginia)
https://dashscope-us.aliyuncs.com/api/v1
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao realizar a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
Substitua {WorkspaceId} pelo seu Workspace ID real.
O escopo de implantação global (região de Frankfurt) suporta apenas chamadas assíncronas.
Edição de imagem
Synchronous
Exemplo de solicitação
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# Singapore region base_url. Base URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If environment variable is not configured, replace the next line with: api_key="sk-xxx"
# API keys differ by region. Get API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
# Supports local files, e.g., "image": "file://umbrella1.png"
content=[
{
"text": "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"
},
{
"image": "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"
},
{
"image": "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp"
}
]
)
print("----sync call, wait a moment----")
rsp = ImageGeneration.call(
model='wan2.6-image',
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
enable_interleave=False,
size="1K"
)
print(rsp)
Exemplo de resposta
A URL expira após 24 horas. Baixe as imagens prontamente.
{
"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
}
}
Asynchronous
Exemplo de solicitação
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# Singapore region base_url. Base URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If environment variable is not configured, replace the next line with: api_key="sk-xxx"
# API keys differ by region. Get API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# Create asynchronous task
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[
{'text': 'Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2'},
{'image': 'https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png'},
{'image': 'https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp'}
]
)
response = ImageGeneration.async_call(
model="wan2.6-image",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
enable_interleave=False,
size="1K"
)
if response.status_code == 200:
print("Task created successfully:", response)
return response # Return task ID
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# Wait for task completion
def wait_for_completion(task_response):
print("Waiting for task completion...")
status = ImageGeneration.wait(task=task_response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("Task succeeded!")
print("Response:", status)
else:
raise Exception(f"Task failed with status: {status.output.task_status}")
# Fetch asynchronous task info
def fetch_task_status(task):
print("Fetching task status...")
status = ImageGeneration.fetch(task=task, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print("Task status:", status.output.task_status)
print("Response details:", status)
else:
print(f"Failed to fetch status: {status.code} - {status.message}")
# Cancel asynchronous task
def cancel_task(task):
print("Canceling task...")
response = ImageGeneration.cancel(task=task, api_key=api_key)
if response.status_code == HTTPStatus.OK:
print("Task canceled successfully:", response.output.task_status)
else:
print(f"Failed to cancel task: {response.code} - {response.message}")
# Main execution flow
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
Exemplo de resposta
-
Exemplo de resposta de criação de tarefa
{ "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 } }
-
Exemplo de resposta de consulta de resultado da tarefa
A URL expira após 24 horas. Baixe as imagens prontamente.
{ "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 } }
Saída intercalada de texto e imagem
Synchronous (streaming only)
Exemplo de solicitação
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# Singapore region URL. Base URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If environment variable is not configured, replace the next line with: api_key="sk-xxx"
# API keys differ by region. Get API key: https://www.alibabacloud.com/help/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 only
negative_prompt="",
enable_interleave=True,
max_images=3,
size="1280*1280"
)
print("Streaming output results:")
for stream_res in image_stream_res:
print(stream_res)
if __name__ == "__main__":
sync_call_with_stream()
Exemplo de resposta
A URL expira após 24 horas. Baixe as imagens prontamente.
{"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"}}
Asynchronous
Exemplo de solicitação
Nota: Chamadas assíncronas não requerem o parâmetro stream
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
from http import HTTPStatus
# Singapore region URL. Base URLs differ by region.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# If environment variable is not configured, replace the next line with: api_key="sk-xxx"
# API keys differ by region. Get API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def main():
"""Asynchronous call - Text-image output"""
print("========== wan2.6-image Asynchronous call - Text-image output ==========")
image_message = Message(
role="user",
content=[
{
"text": "Give me a three-image tutorial for stir-fried pork with chili peppers"
}
]
)
# Create asynchronous task
print("---async call, creating task----")
response = ImageGeneration.async_call(
model="wan2.6-image",
api_key=api_key,
messages=[image_message],
# Asynchronous calls do not require stream parameter
negative_prompt="",
enable_interleave=True,
max_images=3,
size="1280*1280"
)
if response.status_code == HTTPStatus.OK:
print(f"Task created successfully:")
print(response)
# Wait for task completion
print("\n---waiting for task completion----")
status = ImageGeneration.wait(task=response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("Task completed!")
print(f"Results:")
print(status)
else:
print(f"Task failed, status: {status.output.task_status}")
else:
print(f"Task creation failed: {response.code} - {response.message}")
if __name__ == "__main__":
try:
main()
except Exception as e:
print(f"Execution error: {str(e)}")
import traceback
traceback.print_exc()
Exemplo de resposta
-
Exemplo de resposta de criação de tarefa
{ "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 } }
-
Exemplo de resposta de consulta de resultado da tarefa
A URL expira após 24 horas. Baixe as imagens prontamente.
{ "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
Os parâmetros do SDK estão alinhados com a interface HTTP, encapsulados conforme as convenções da linguagem.
O SDK gerencia chamadas assíncronas internamente e suporta invocação síncrona e assíncrona.
A duração real depende do tamanho da fila e da carga do service.
Requer DashScope Java SDK versão 2.22.6 ou posterior.
O base_url e a chave de API não são intercambiáveis entre regiões. Exemplos para a região de Singapore:
Singapore
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
US (Virginia)
https://dashscope-us.aliyuncs.com/api/v1
China (Beijing)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Ao fazer a chamada, substitua {WorkspaceId} pelo seu workspace ID real.
Germany (Frankfurt)
https://{WorkspaceId}.eu-central-1.maas.aliyuncs.com/api/v1
Substitua {WorkspaceId} pelo seu Workspace ID real.
O escopo de implantação global (região de Frankfurt) suporta apenas chamadas assíncronas.
Edição de imagens
Synchronous
Exemplo de solicitação
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Arrays;
import java.util.Collections;
/**
* wan2.6-image Image editing - Synchronous call example
*/
public class Main {
static {
// Singapore region URL. Base URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
// API keys differ by region. Get API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException, UploadFileException {
// Build multi-image input message
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Supports multi-image input; provide multiple reference images
Collections.singletonMap("text", "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"),
Collections.singletonMap("image", "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"),
Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp")
)).build();
// Image editing uses standard synchronous call; no need to set stream or enable_interleave
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-image")
.messages(Collections.singletonList(message))
.n(1)
.size("1K")
.negativePrompt("")
.promptExtend(true)
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call for image editing, wait a moment----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
basicCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
Exemplo de resposta
A URL expira após 24 horas. Baixe as imagens prontamente.
{
"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": ""
}
Asynchronous
Exemplo de solicitação
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Arrays;
import java.util.Collections;
/**
* wan2.6-image Image editing - Asynchronous call example
*/
public class Main {
static {
// Singapore region URL. Base URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
// API keys differ by region. Get API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void asyncCall() throws ApiException, NoApiKeyException, UploadFileException {
// Build multi-image input message
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Arrays.asList(
// Supports multi-image input; provide multiple reference images
Collections.singletonMap("text", "Generate a tomato and egg stir-fry based on the style of image 1 and the background of image 2"),
Collections.singletonMap("image", "https://cdn.wanx.aliyuncs.com/tmp/pressure/umbrella1.png"),
Collections.singletonMap("image", "https://img.alicdn.com/imgextra/i3/O1CN01SfG4J41UYn9WNt4X1_!!6000000002530-49-tps-1696-960.webp")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-image")
.n(1)
.size("1K")
.negativePrompt("")
.promptExtend(true)
.messages(Arrays.asList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---async call for image editing, creating task----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println("Task creation result:");
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// Wait for task completion
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
System.out.println("\n---waiting for task completion----");
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
System.out.println("Task completion result:");
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
asyncCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
Exemplo de resposta
-
Exemplo de resposta de criação de tarefa
{ "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 }
-
Exemplo de resposta de consulta de resultado da tarefa
A URL expira após 24 horas. Baixe as imagens prontamente.
{ "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 } }
Saída intercalada de texto e imagem
Synchronous call (streaming only)
Exemplo de solicitação
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import io.reactivex.Flowable;
import java.util.Collections;
/**
* wan2.6-image Text-image output - Streaming call example
*/
public class Main {
static {
// Singapore region URL. Base URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
// API keys differ by region. Get API key: https://www.alibabacloud.com/help/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();
// Text-image output requires streaming call
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-image")
.messages(Collections.singletonList(message))
.stream(true) // Must enable streaming output
.enableInterleave(true)
.size("1280*1280")
.negativePrompt("")
.maxImages(3)
.build();
ImageGeneration imageGeneration = new ImageGeneration();
try {
System.out.println("---stream call for image interleave----");
Flowable<ImageGenerationResult> resultFlowable = imageGeneration.streamCall(param);
resultFlowable.blockingForEach(result -> {
System.out.println(JsonUtils.toJson(result));
});
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
}
public static void main(String[] args) {
try {
streamCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
System.exit(0);
}
}
Exemplo de resposta
A URL expira após 24 horas. Baixe as imagens prontamente.
{"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":""}
Asynchronous call
Exemplo de solicitação
Nota: Chamadas assíncronas não exigem o parâmetro 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-image output - Asynchronous call example
*/
public class Main {
static {
// Singapore region URL. Base URLs differ by region.
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// If environment variable is not configured, replace the next line with: apiKey="sk-xxx"
// API keys differ by region. Get API key: https://www.alibabacloud.com/help/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();
// Wait for task completion
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
System.out.println("\n---waiting for task completion----");
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
System.out.println("Task completion result:");
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
asyncCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}
Exemplo de resposta
-
Exemplo de resposta de criação de tarefa
{ "requestId": "7d6c5760-334b-48c4-9b1e-08ee9c7fexxx", "output": { "task_id": "1bb9d9fa-bf1a-43dc-b5fe-366c1dc70xxx", "task_status": "PENDING" }, "status_code": 200, "code": "", "message": "" }
-
Exemplo de resposta de consulta de resultado da tarefa
A URL expira após 24 horas. Baixe as imagens prontamente.
{ "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": "" }
Limitações
Validade dos dados: O
task_idda tarefa e aurlda imagem são retidos por apenas 24 horas. Após esse período, não é possível consultá-los ou baixá-los.Moderação de conteúdo: Tanto o
promptde entrada quanto a imagem de saída passam por moderação de conteúdo. Conteúdo não compatível retorna um erroIPInfringementSuspectouDataInspectionFailed. Consulte Códigos de erro.
Faturamento e limitação de taxa
Cotas gratuitas e preços: Preços do modelo.
Para limites de taxa do modelo, consulte Wanxiang.
A cobrança é feita por imagem gerada com sucesso. Chamadas com falha não incorrem em custos e não consomem a cota gratuita.
Códigos de erro
Se a chamada do modelo falhar e retornar uma mensagem de erro, consulte Códigos de erro para resolução.
FAQ
P: Como visualizo os custos de inferência e o volume de chamadas de um modelo?
R: Consulte Consulta de fatura e gerenciamento de custos.
P: Por que não consigo executar os exemplos de código?
R: Atualize seu SDK para a versão mais recente. Instalar SDK.