Wan Text-to-Image モデルは、テキストプロンプトから画像を生成し、芸術的なスタイルやリアルな写真効果をサポートします。
クイックリンク:オンラインで試す (シンガポール | 米国 (バージニア) | 中国 (北京)) | Wan 公式サイト
Wan 公式サイトの機能は API の機能と異なる場合があります。このドキュメントでは API について説明しており、変更があり次第更新されます。
前提条件
呼び出しを行う前に、API キーを取得し、API キーを環境変数としてエクスポートしてください。SDK を使用して呼び出しを行うには、DashScope SDK をインストールします。
シンガポール、米国 (バージニア) 、中国 (北京) リージョンには、それぞれ別の API キーとリクエストエンドポイントがあります。これらは相互に使用することはできません。リージョンをまたいだ呼び出しは、認証失敗やサービスエラーにつながります。詳細については、「リージョンとサービスデプロイ範囲の選択」をご参照ください。
HTTP 同期呼び出し (wan2.6)
このセクションの API は新しいプロトコルを使用しており、wan2.6 モデルのみをサポートします。
単一リクエストで結果を取得します。ほとんどのユースケースで推奨されます。
シンガポール
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
米国 (バージニア)
POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
中国 (北京)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
グローバルデプロイメントスコープ (ドイツ (フランクフルト) リージョン) は、非同期呼び出しのみをサポートします。
リクエストパラメーター | Text-to-Image |
リクエストヘッダー | |
Content-Type リクエストのコンテンツタイプは | |
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 | |
リクエストボディ | |
model モデル名。例:wan2.6-t2i。 説明 wan2.5 およびそれ以前のモデルについては、HTTP 呼び出しのために「HTTP 非同期呼び出し」をご参照ください。 | |
input 入力オブジェクト。 | |
parameters 画像生成パラメーター。 |
レスポンスパラメーター | タスクの正常な実行タスクデータ (タスクステータスと画像 URL) は 24 時間のみ保持され、その後自動的に消去されます。生成された画像は速やかに保存してください。 タスクの実行失敗タスクが失敗した場合、API はエラー情報を返します。code と message フィールドから原因を特定してください。「エラーコード」をご参照ください。 |
output 出力オブジェクト。 | |
usage リクエストの使用状況統計。成功した結果のみがカウントされます。 | |
request_id 追跡とトラブルシューティングのためのユニークなリクエスト識別子。 | |
code エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 | |
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 |
HTTP 非同期呼び出し (wan2.6)
このセクションの API は新しいプロトコルを使用しており、wan2.6 モデルのみをサポートします。
タスクフローには、タスクの作成 -> 結果のポーリングという2つのコアステップが含まれます。プロセスは以下の通りです:
ステップ 1:タスクを作成してタスク ID を取得
シンガポール
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
米国 (バージニア)
POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/image-generation/generation
中国 (北京)
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/image-generation/generation
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
ドイツ (フランクフルト)
POST https://<u><u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u></u>/api/v1/services/aigc/image-generation/generation
呼び出しを行う際、WorkspaceId をご利用の ワークスペース ID に置き換えてください。
-
タスクが作成されたら、返された
task_idを使用して結果をクエリします。task_idは 24 時間有効です。 重複するタスクを作成しないでください。 代わりに、ポーリングを使用して結果を取得してください。 -
初心者向けのガイダンスについては、「Postman または cURL で API を呼び出す」をご参照ください。
リクエストパラメーター | Text-to-Image |
リクエストヘッダー | |
Content-Type リクエストのコンテンツタイプ。 | |
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 | |
X-DashScope-Async 非同期処理を有効にします。HTTP リクエストは非同期呼び出しのみをサポートします。 重要
このリクエストヘッダーがない場合、「current user api does not support synchronous calls」というエラーが返されます。 | |
リクエストボディ | |
model モデル名。例:wan2.6-t2i。 説明 wan2.5 およびそれ以前のモデルについては、「HTTP 非同期呼び出し」をご参照ください。 | |
input 入力オブジェクト。 | |
parameters 画像生成パラメーター。 |
レスポンスパラメーター | 成功した応答
エラー応答タスクの作成に失敗しました。「エラーコード」をご参照ください。
|
output 出力オブジェクト。 | |
request_id 追跡とトラブルシューティングのためのユニークなリクエスト識別子。 | |
code エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 | |
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 |
ステップ 2:タスク ID で結果をクエリ
シンガポール
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
米国 (バージニア)
GET https://dashscope-us.aliyuncs.com/api/v1/tasks/{task_id}
中国 (北京)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
ドイツ (フランクフルト)
GET https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1/tasks/{task_id}
呼び出しを行う際、{WorkspaceId} を実際のワークスペース ID に置き換えてください。
-
ポーリングの推奨:画像生成には時間がかかります。10 秒などの適切な間隔でポーリングメカニズムを使用してください。
-
タスク状態の遷移:PENDING → RUNNING → SUCCEEDED または FAILED。
-
結果リンク:タスクが成功すると、24 時間有効な画像 URL が返されます。画像をダウンロードして、Object Storage Service (OSS) などの永続ストレージに保存してください。
リクエストパラメーター | タスク結果のクエリ
|
リクエストヘッダー | |
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 | |
URL パスパラメーター | |
task_id タスクの ID。 |
レスポンスパラメーター | タスクの正常な実行タスクデータ (タスクステータスと画像 URL) は 24 時間のみ保持され、その後自動的に消去されます。生成された画像は速やかに保存してください。 タスクの実行失敗タスクが失敗した場合、API はエラー情報を返します。code と message フィールドから原因を特定してください。「エラーコード」をご参照ください。 |
output タスクの出力情報。 | |
usage リクエストの使用状況統計。成功した結果のみがカウントされます。 | |
request_id 追跡とトラブルシューティングのためのユニークなリクエスト識別子。 | |
code エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 | |
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 |
HTTP 非同期呼び出し (wan2.5 およびそれ以前のモデル)
この API は古いプロトコルを使用しており、wan2.5 およびそれ以前のモデルのみをサポートします。
Text-to-Image タスクはかなりの時間 (通常 1〜2 分) がかかるため、API は非同期呼び出しを使用します。フローには、タスクの作成 -> 結果のポーリングという2つのコアステップが含まれます。プロセスは以下の通りです:
処理時間は、タスクキューとサービスステータスに依存します。
ステップ 1:タスクを作成してタスク ID を取得
シンガポール
POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
北京
POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text2image/image-synthesis
-
タスクの作成後、返された
task_idを使用して結果をクエリしてください。task_idは 24 時間有効です。重複するタスクは作成しないでください。代わりに、ポーリングを使用して結果を取得してください。 -
初心者向けのガイダンスについては、「Postman または cURL で API を呼び出す」をご参照ください。
リクエストパラメーター | Text-to-Imageシンガポールと北京リージョンの API キーは異なります。API キーを取得 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用している場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis に置き換えてください Text-to-Image (ネガティブプロンプトあり)生成される画像に「人々」が現れないようにするために `negative_prompt` を使用します。 シンガポールと北京リージョンの API キーは異なります。API キーを取得 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用している場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/video-generation/video-synthesis に置き換えてください |
リクエストヘッダー | |
Content-Type リクエストのコンテンツタイプ。 | |
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 | |
X-DashScope-Async 非同期処理を有効にします。HTTP リクエストは非同期呼び出しのみをサポートします。値は 重要
このリクエストヘッダーがない場合、「current user api does not support synchronous calls」というエラーが返されます。 | |
リクエストボディ | |
model モデル名。Text-to-Image モデルについては、「モデルリスト」をご参照ください。 例:wan2.5-t2i-preview。 説明 wan2.6 モデルへの HTTP 呼び出しについては、「HTTP 同期呼び出し」および「HTTP 非同期呼び出し」をご参照ください。 | |
input プロンプトを含む入力オブジェクト。 | |
parameters 画像生成パラメーター。 |
レスポンスパラメーター | 成功した応答
エラー応答タスクの作成に失敗しました。「エラーコード」をご参照ください。
|
output タスクの出力情報。 | |
request_id 追跡とトラブルシューティングのためのユニークなリクエスト識別子。 | |
code エラーコード。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 | |
message 詳細なエラーメッセージ。失敗したリクエストに対してのみ返されます。「エラーコード」をご参照ください。 |
ステップ 2:タスク ID で結果をクエリ
シンガポール
GET https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/tasks/{task_id}
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
中国 (北京)
GET https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/tasks/{task_id}
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
-
ポーリングの推奨:画像生成には時間がかかります。10 秒などの適切な間隔でポーリングメカニズムを使用してください。
-
タスク状態の遷移:PENDING → RUNNING → SUCCEEDED または FAILED。
-
結果リンク:タスクが成功すると、24 時間有効な画像 URL が返されます。画像をダウンロードして、Object Storage Service (OSS) などの永続ストレージに保存してください。
リクエストパラメーター | タスク結果のクエリ
API キーはリージョンごとに異なります。詳細については、「API キーの取得」をご参照ください。 中国 (北京) リージョンでモデルを使用する場合、
|
リクエストヘッダー | |
Authorization Model Studio API キーでリクエストを認証します。例:Bearer sk-xxxx。 | |
URL パスパラメーター | |
task_id タスクの ID。 |
レスポンスパラメーター | タスクの正常な実行画像 URL は 24 時間のみ有効で、その後自動的に消去されます。生成された画像は速やかに保存してください。 タスク失敗タスクが失敗すると、 部分的なタスクの失敗モデルはタスクごとに複数のイメージを生成できます。少なくとも 1 つが成功した場合、タスクのステータスは タスククエリの期限切れ
|
output タスクの出力情報。 | |
usage リクエストの使用状況統計。成功した結果のみがカウントされます。 | |
request_id 追跡とトラブルシューティングのためのユニークなリクエスト識別子。 |
DashScope Python SDK
SDK のパラメーター名は HTTP API と一致していますが、構造は Python に合わせて調整されています。
Text-to-Image タスクはかなりの時間がかかるため、SDK は HTTP 非同期呼び出しプロセスをカプセル化し、同期および非同期呼び出しの両方をサポートします。
処理時間は、タスクキューとサービスステータスに依存します。
wan2.6
以下のコードは wan2.6 モデル専用です。
以下のコードを実行する前に、DashScope Python SDK のバージョンが 1.25.7 以上であることを確認してください。更新するには、「SDK のインストール」をご参照ください。
base_url と API キーはリージョン固有です。 次の例は、シンガポール リージョンでの呼び出しを示しています。
シンガポール
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
米国 (バージニア)
https://dashscope-us.aliyuncs.com/api/v1
中国 (北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
ドイツ (フランクフルト)
https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1
WorkspaceId を実際のワークスペース ID に置き換えてください。
グローバルデプロイメントスコープ (ドイツ (フランクフルト) リージョン) は、非同期呼び出しのみをサポートします。
同期呼び出し
リクエスト例
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Message
# 以下はシンガポールリージョンの base_url です。base_url はリージョン固有です。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョン固有です。API キーを取得するには:https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
message = Message(
role="user",
content=[
{
'text': 'A flower shop with exquisite windows, a beautiful wooden door, and flowers on display'
}
]
)
print("----Sync call, please wait a moment----")
rsp = ImageGeneration.call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
print(rsp)
レスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{
"status_code": 200,
"request_id": "820dd0db-eb42-4e05-8d6a-1ddb4axxxxxx",
"code": "",
"message": "",
"output": {
"text": null,
"finish_reason": null,
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx",
"type": "image"
}
]
}
}
],
"audio": null,
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"characters": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}非同期呼び出し
リクエスト例
import os
import dashscope
from dashscope.aigc.image_generation import ImageGeneration
from dashscope.api_entities.dashscope_response import Role, Message
from http import HTTPStatus
# 以下はシンガポールリージョンの base_url です。base_url はリージョン固有です。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# API キーはリージョン固有です。API キーを取得するには:https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
# 非同期タスクを作成
def create_async_task():
print("Creating async task...")
message = Message(
role="user",
content=[{'text': 'A flower shop with exquisite windows, a beautiful wooden door, and flowers on display'}]
)
response = ImageGeneration.async_call(
model="wan2.6-t2i",
api_key=api_key,
messages=[message],
negative_prompt="",
prompt_extend=True,
watermark=False,
n=1,
size="1280*1280"
)
if response.status_code == 200:
print("Task created successfully:", response)
return response
else:
raise Exception(f"Failed to create task: {response.code} - {response.message}")
# タスクが完了するのを待つ
def wait_for_completion(task_response):
print("Waiting for task completion...")
status = ImageGeneration.wait(task=task_response, api_key=api_key)
if status.output.task_status == "SUCCEEDED":
print("Task succeeded!")
print("Response:", status)
else:
raise Exception(f"Task failed with status: {status.output.task_status}")
# 非同期タスク情報を取得
def fetch_task_status(task):
print("Fetching task status...")
status = ImageGeneration.fetch(task=task, api_key=api_key)
if status.status_code == HTTPStatus.OK:
print("Task status:", status.output.task_status)
print("Response details:", status)
else:
print(f"Failed to fetch status: {status.code} - {status.message}")
# 非同期タスクをキャンセル
def cancel_task(task):
print("Canceling task...")
response = ImageGeneration.cancel(task=task, api_key=api_key)
if response.status_code == HTTPStatus.OK:
print("Task canceled successfully:", response.output.task_status)
else:
print(f"Failed to cancel task: {response.code} - {response.message}")
# メイン実行フロー
if __name__ == "__main__":
task = create_async_task()
wait_for_completion(task)
レスポンス例
タスク作成のレスポンス例
{ "status_code": 200, "request_id": "c4f11410-ea42-4996-957d-9c82f9xxxxxx", "code": "", "message": "", "output": { "text": null, "finish_reason": null, "choices": null, "audio": null, "task_id": "f470bbfd-d955-4165-935b-d35b8eexxxxxx", "task_status": "PENDING" }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0 } }タスク結果クエリのレスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{ "status_code": 200, "request_id": "7e57e7e8-00b0-4534-9aff-fe31e0xxxxxx", "code": null, "message": "", "output": { "text": null, "finish_reason": null, "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-bj.oss-cn-beijing.aliyuncs.com/xxxxxx.png?Expires=xxxxxx", "type": "image" } ] } } ], "audio": null, "task_id": "f470bbfd-d955-4165-935b-d35b8exxxxxx", "task_status": "SUCCEEDED", "submit_time": "2026-01-09 17:18:17.901", "scheduled_time": "2026-01-09 17:18:17.941", "end_time": "2026-01-09 17:18:45.544", "finished": true }, "usage": { "input_tokens": 0, "output_tokens": 0, "characters": 0, "size": "1280*1280", "total_tokens": 0, "image_count": 1 } }
wan2.5 およびそれ以前のモデル
以下のコードは wan2.5 およびそれ以前のモデル専用です。
以下のコードを実行する前に、DashScope Python SDK のバージョンが 1.25.2 以上であることを確認してください。
バージョンが低すぎると、「url error, please check url!」などのエラーが発生する可能性があります。更新するには、「SDK のインストール」をご参照ください。
base_url と API キーはリージョン固有です。次の例は、シンガポール リージョンでの呼び出しを示します:
シンガポール
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
中国 (北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
同期呼び出し
リクエスト例
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用している場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# シンガポールと北京リージョンの API キーは異なります。API キーを取得するには:https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
print('----Sync call, please wait a moment----')
rsp = ImageSynthesis.call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print('response: %s' % rsp)
if rsp.status_code == HTTPStatus.OK:
# 現在のディレクトリに画像を保存
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('sync_call Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
レスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{
"status_code": 200,
"request_id": "9d634fda-5fe9-9968-a908-xxxxxx",
"code": null,
"message": "",
"output": {
"task_id": "d35658e4-483f-453b-b8dc-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png",
"orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
"actual_prompt": "An exquisite flower shop, with elegant carvings on the windows and a beautiful wooden door with a brass handle. Inside, a variety of colorful flowers such as roses, tulips, and lilies are displayed. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition."
}],
"submit_time": "2025-01-08 19:36:01.521",
"scheduled_time": "2025-01-08 19:36:01.542",
"end_time": "2025-01-08 19:36:13.270",
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}
非同期呼び出し
リクエスト例
from http import HTTPStatus
from urllib.parse import urlparse, unquote
from pathlib import PurePosixPath
import requests
from dashscope import ImageSynthesis
import os
import dashscope
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用している場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1 に置き換えてください
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
# 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:api_key="sk-xxx"
# シンガポールと北京リージョンの API キーは異なります。API キーを取得するには:https://www.alibabacloud.com/help/en/model-studio/get-api-key
api_key = os.getenv("DASHSCOPE_API_KEY")
def async_call():
print('----Create task----')
task_info = create_async_task()
print('----Wait for task to complete, then save image----')
wait_async_task(task_info)
# 非同期タスクを作成
def create_async_task():
rsp = ImageSynthesis.async_call(api_key=api_key,
model="wan2.5-t2i-preview",
prompt="A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
negative_prompt="",
n=1,
size='1280*1280',
prompt_extend=True,
watermark=False,
seed=12345)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
return rsp
# 非同期タスクが完了するのを待つ
def wait_async_task(task):
rsp = ImageSynthesis.wait(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output)
# 現在のディレクトリにファイルを保存
for result in rsp.output.results:
file_name = PurePosixPath(unquote(urlparse(result.url).path)).parts[-1]
with open('./%s' % file_name, 'wb+') as f:
f.write(requests.get(result.url).content)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
# 非同期タスク情報を取得
def fetch_task_status(task):
status = ImageSynthesis.fetch(task=task, api_key=api_key)
print(status)
if status.status_code == HTTPStatus.OK:
print(status.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(status.status_code, status.code, status.message))
# 非同期タスクをキャンセル。PENDING 状態のタスクのみキャンセル可能。
def cancel_task(task):
rsp = ImageSynthesis.cancel(task=task, api_key=api_key)
print(rsp)
if rsp.status_code == HTTPStatus.OK:
print(rsp.output.task_status)
else:
print('Failed, status_code: %s, code: %s, message: %s' %
(rsp.status_code, rsp.code, rsp.message))
if __name__ == '__main__':
async_call()
レスポンス例
タスク作成のレスポンス例
{ "status_code": 200, "request_id": "31b04171-011c-96bd-ac00-f0383b669cc7", "code": "", "message": "", "output": { "task_id": "4f90cf14-a34e-4eae-xxxxxxxx", "task_status": "PENDING", "results": [] }, "usage": null }タスク結果クエリのレスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{ "status_code": 200, "request_id": "9d634fda-5fe9-9968-a908-xxxxxx", "code": null, "message": "", "output": { "task_id": "d35658e4-483f-453b-b8dc-xxxxxx", "task_status": "SUCCEEDED", "results": [{ "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/xxx.png", "orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display", "actual_prompt": "An exquisite flower shop, with elegant carvings on the windows and a beautiful wooden door with a brass handle. Inside, a variety of colorful flowers such as roses, tulips, and lilies are displayed. The background is a warm indoor scene with soft light, creating a peaceful and comfortable atmosphere. High-definition realistic photography, close-up center composition." }], "submit_time": "2025-01-08 19:36:01.521", "scheduled_time": "2025-01-08 19:36:01.542", "end_time": "2025-01-08 19:36:13.270", "task_metrics": { "TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0 } }, "usage": { "image_count": 1 } }
DashScope Java SDK
SDK のパラメーター名は HTTP API と一致していますが、構造は Java に合わせて調整されています。
Text-to-Image タスクはかなりの時間がかかることがあります。SDK は HTTP 非同期呼び出しフローをカプセル化し、同期および非同期呼び出しの両方をサポートします。
処理時間は、タスクキューとサービスステータスに依存します。
wan2.6
以下のコードは wan2.6-t2i モデルにのみ適用されます。
以下のコードを実行する前に、DashScope Java SDK のバージョンが 2.22.6 以降であることを確認してください。
base_url と API キーはリージョンごとに異なり、相互に交換して使用することはできません。次の例は、シンガポール リージョンで呼び出しを行う方法を示しています。
シンガポール
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
米国 (バージニア)
https://dashscope-us.aliyuncs.com/api/v1
中国 (北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
呼び出す際、WorkspaceId を実際のワークスペース ID に置き換えてください。
ドイツ (フランクフルト)
https://<u>{WorkspaceId}.eu-central-1.maas.aliyuncs.com</u>/api/v1
WorkspaceId を実際のワークスペース ID に置き換えてください。
グローバルデプロイメントスコープ (ドイツ (フランクフルト) リージョン) は、非同期呼び出しのみをサポートします。
同期呼び出し
リクエスト例
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;
public class Main {
static {
// これはシンガポールリージョンの URL です。base_url はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// API キーはリージョンごとに異なります。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 {
ImageGenerationMessage message = ImageGenerationMessage.builder()
.role("user")
.content(Collections.singletonList(
Collections.singletonMap("text", "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageGeneration.call(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
basicCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}レスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{
"status_code": 200,
"request_id": "50b57166-eaaa-4f17-b1e0-35a5ca88672c",
"code": "",
"message": "",
"output": {
"choices": [
{
"finish_reason": "stop",
"message": {
"role": "assistant",
"content": [
{
"image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx",
"type": "image"
}
]
}
}
],
"finished": true
},
"usage": {
"input_tokens": 0,
"output_tokens": 0,
"image_count": 1,
"size": "1280*1280",
"total_tokens": 0
}
}非同期呼び出し
リクエスト例
import com.alibaba.dashscope.aigc.imagegeneration.*;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.Collections;
public class Main {
static {
// これはシンガポールリージョンの URL です。base_url はリージョンによって異なります。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行をご利用の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// API キーはリージョンごとに異なります。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", "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
)).build();
ImageGenerationParam param = ImageGenerationParam.builder()
.apiKey(apiKey)
.model("wan2.6-t2i")
.n(1)
.size("1280*1280")
.negativePrompt("")
.promptExtend(true)
.watermark(false)
.messages(Collections.singletonList(message))
.build();
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = null;
try {
System.out.println("---async call, creating task----");
result = imageGeneration.asyncCall(param);
} catch (ApiException | NoApiKeyException | UploadFileException e) {
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
// タスクが完了するのを待つ
waitTask(taskId);
}
public static void waitTask(String taskId) throws ApiException, NoApiKeyException {
ImageGeneration imageGeneration = new ImageGeneration();
ImageGenerationResult result = imageGeneration.wait(taskId, apiKey);
System.out.println(JsonUtils.toJson(result));
}
public static void main(String[] args) {
try {
asyncCall();
} catch (ApiException | NoApiKeyException | UploadFileException e) {
System.out.println(e.getMessage());
}
}
}レスポンスの例
タスク作成のレスポンス例
{ "status_code": 200, "request_id": "9cd85950-2e26-4b2c-b562-1694cf9288e5", "code": "", "message": "", "output": { "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba", "task_status": "PENDING" }, "usage": null }
タスク結果クエリのレスポンス例
URL は 24 時間有効です。画像を速やかにダウンロードする必要があります。
{ "status_code": 200, "request_id": "cbdf1424-306e-4a52-82f3-8bf5d8a99103", "code": "", "message": "", "output": { "choices": [ { "finish_reason": "stop", "message": { "role": "assistant", "content": [ { "image": "https://dashscope-result-sh.oss-cn-shanghai.aliyuncs.com/xxx.png?Expires=xxx", "type": "image" } ] } } ], "task_id": "4c861fbe-af89-4a2f-8fc5-4bb15c3139ba", "task_status": "SUCCEEDED", "submit_time": "2026-01-16 16:36:06.556", "scheduled_time": "2026-01-16 16:36:06.591", "end_time": "2026-01-16 16:36:25.190", "finished": true }, "usage": { "input_tokens": 0, "output_tokens": 0, "size": "1280*1280", "total_tokens": 0, "image_count": 1 } }
wan2.5 以前のモデル
以下のコードは、wan2.5 以前のモデルにのみ適用されます。
以下のコードを実行する前に、DashScope Java SDK のバージョンが 2.22.2 以降であることを確認してください。
バージョンが古すぎると、「url error, please check url!」などのエラーが発生する可能性があります。更新するには、「SDK のインストール」をご参照ください。
base_url と API キーはリージョンごとに異なり、相互に交換して使用することはできません。以下の例は、シンガポールリージョンで呼び出しを行う方法を示しています:
シンガポール
https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1
呼び出す際は、WorkspaceId を実際のワークスペース ID に置き換えてください。
中国 (北京)
https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
呼び出す際は、WorkspaceId を実際のワークスペース ID に置き換えてください。
同期呼び出し
リクエスト例
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisListResult;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.task.AsyncTaskListParam;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// これはシンガポールリージョンの URL です。中国 (北京) リージョンのモデルを使用する場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1 に置き換えてください。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// シンガポールリージョンと中国 (北京) リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public static void basicCall() throws ApiException, NoApiKeyException {
// パラメーターを設定します
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
.n(1)
.size("1280*1280")
.negativePrompt("")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
System.out.println("---sync call, please wait a moment----");
result = imageSynthesis.call(param);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
}
public static void listTask() throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
AsyncTaskListParam param = AsyncTaskListParam.builder().build();
param.setApiKey(apiKey);
ImageSynthesisListResult result = is.list(param);
System.out.println(result);
}
public static void fetchTask(String taskId) throws ApiException, NoApiKeyException {
ImageSynthesis is = new ImageSynthesis();
// DASHSCOPE_API_KEY 環境変数が設定されている場合、apiKey を null に設定できます。
ImageSynthesisResult result = is.fetch(taskId, apiKey);
System.out.println(result.getOutput());
System.out.println(result.getUsage());
}
public static void main(String[] args){
try{
basicCall();
//listTask();
}catch(ApiException|NoApiKeyException e){
System.out.println(e.getMessage());
}
}
}レスポンス例
URL の有効期間は 24 時間です。イメージは速やかにダウンロードする必要があります。
{
"request_id": "22f9c744-206c-9a78-899a-xxxxxx",
"output": {
"task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx",
"task_status": "SUCCEEDED",
"results": [{
"orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display",
"actual_prompt": "A flower shop with exquisitely carved windows and a beautiful dark wooden door slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are on display inside, vibrant in color and fragrant. The background is a cozy indoor scene with soft light streaming through the windows onto the flowers. High-definition realistic photography, medium shot composition.",
"url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png"
}],
"task_metrics": {
"TOTAL": 1,
"SUCCEEDED": 1,
"FAILED": 0
}
},
"usage": {
"image_count": 1
}
}非同期呼び出し
リクエスト例
// Copyright (c) Alibaba, Inc. and its affiliates.
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesis;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisParam;
import com.alibaba.dashscope.aigc.imagesynthesis.ImageSynthesisResult;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.utils.Constants;
import com.alibaba.dashscope.utils.JsonUtils;
import java.util.HashMap;
import java.util.Map;
public class Main {
static {
// これはシンガポールリージョンの URL です。中国 (北京) リージョンのモデルを使用する場合は、URL を https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1 に置き換えてください。
Constants.baseHttpApiUrl = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
// 環境変数を設定していない場合は、次の行を実際の Model Studio API キーに置き換えてください:apiKey="sk-xxx"
// シンガポールリージョンと中国 (北京) リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください。
static String apiKey = System.getenv("DASHSCOPE_API_KEY");
public void asyncCall() {
System.out.println("---create task----");
String taskId = this.createAsyncTask();
System.out.println("---wait task done then return image url----");
this.waitAsyncTask(taskId);
}
/**
* 非同期タスクを作成します
* @return taskId
*/
public String createAsyncTask() {
// パラメーターを設定します
Map<String, Object> parameters = new HashMap<>();
parameters.put("prompt_extend", true);
parameters.put("watermark", false);
parameters.put("seed", 12345);
ImageSynthesisParam param =
ImageSynthesisParam.builder()
.apiKey(apiKey)
.model("wan2.5-t2i-preview")
.prompt("A flower shop with exquisite windows, a beautiful wooden door, and flowers on display")
.n(1)
.size("1280*1280)
.negativePrompt("")
.parameters(parameters)
.build();
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
result = imageSynthesis.asyncCall(param);
} catch (Exception e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
String taskId = result.getOutput().getTaskId();
System.out.println("taskId=" + taskId);
return taskId;
}
/**
* 非同期タスクの完了を待ちます
* @param taskId タスク ID
* */
public void waitAsyncTask(String taskId) {
ImageSynthesis imageSynthesis = new ImageSynthesis();
ImageSynthesisResult result = null;
try {
// 環境変数を設定した後、ここで apiKey を null に設定できます
result = imageSynthesis.wait(taskId, apiKey);
} catch (ApiException | NoApiKeyException e){
throw new RuntimeException(e.getMessage());
}
System.out.println(JsonUtils.toJson(result));
System.out.println(JsonUtils.toJson(result.getOutput()));
}
public static void main(String[] args){
Main main = new Main();
main.asyncCall();
}
}レスポンス例
タスク作成のレスポンス例
{ "request_id": "5dbf9dc5-4f4c-9605-85ea-542f97709ba8", "output": { "task_id": "7277e20e-aa01-4709-xxxxxxxx", "task_status": "PENDING" } }タスク結果のクエリのレスポンス例
{ "request_id": "22f9c744-206c-9a78-899a-xxxxxx", "output": { "task_id": "4a0f8fc6-03fb-4c44-a13a-xxxxxx", "task_status": "SUCCEEDED", "results": [{ "orig_prompt": "A flower shop with exquisite windows, a beautiful wooden door, and flowers on display", "actual_prompt": "A flower shop with exquisitely carved windows and a beautiful dark wooden door slightly ajar. A variety of fresh flowers, including roses, lilies, and sunflowers, are on display inside, vibrant in color and fragrant. The background is a cozy indoor scene with soft light streaming through the windows onto the flowers. High-definition realistic photography, medium shot composition.", "url": "https://dashscope-result-wlcb.oss-cn-wulanchabu.aliyuncs.com/1.png" }], "task_metrics": { "TOTAL": 1, "SUCCEEDED": 1, "FAILED": 0 } }, "usage": { "image_count": 1 } }
制限事項
-
データの有効性:タスクの
task_idとイメージのurlは 24 時間のみ保持されます。この期間を過ぎると、照会またはダウンロードできなくなります。 -
コンテンツモデレーション:入力の
promptと出力イメージの両方に対してコンテンツモデレーションが実行されます。コンプライアンスに違反するコンテンツの場合、IPInfringementSuspectまたはDataInspectionFailedエラーが返されます。詳細については、「エラーコード」をご参照ください。
課金とレート制限
無料クォータと料金については、コンソールでご確認ください。
モデルのレート制限については、Wan シリーズをご参照ください。
課金は、正常に生成されたイメージの数に基づいて行われます。呼び出しが失敗した場合、料金は発生せず、新規ユーザー無料クォータも消費されません。
エラーコード
モデルの呼び出しに失敗し、エラーメッセージが返された場合は、解決策について「エラーコード」をご参照ください。
よくある質問
Q:モデルの推論コストと呼び出しボリュームを確認するにはどうすればよいですか?
A:「請求照会とコスト管理」をご参照ください。