Skip to main content

DashScope Python SDK 1.x レガシー使用方法リファレンス

DashScope Python SDK 1.x インターフェースのレガシー使用方法のクイックリファレンスと、1.x から 2.0 への移行対応表です。既存の 1.x プロジェクト向けの参考資料です。

本ページは、引き続き DashScope Python SDK 1.x を使用している既存プロジェクト向けです。1.x インターフェースの典型的な使用方法をまとめ、対応する 2.0 のコードを示します。
新規プロジェクトでは SDK 2.0 を直接ご利用ください。1.x は凍結メンテナンス(欠陥修正のみ)の段階にあり、1.x と 2.0 は同じ dashscope パッケージ内に共存しています(2.0.1 以降)。既存コードは 1.x 依存関係を削除せずに段階的に移行できます。Assistants / Threads / Runs の API ファミリーは 1.x とともに提供を終了し、サーバー側ではサポートされなくなりました。新規コードでは使用しないでください。

インターフェース移行対応表

能力1.x インターフェース2.0 インターフェース
テキスト生成Generation.call / AioGeneration.callclient.chat.completions.create
マルチモーダル対話MultiModalConversation.callclient.multimodal.chat.create
画像生成ImageSynthesis.call/async_call/fetch/waitclient.images.generate / client.images.jobs.*
動画生成VideoSynthesis.call/async_call/fetch/waitclient.videos.generate / client.videos.jobs.*
音声ファイルの文字起こしTranscription.async_call/fetch/waitclient.audio.asr.transcribe / client.audio.asr.jobs.*
リアルタイム音声認識Recognition.start/send_audio_frame/stopclient.audio.asr.recognize(...) context manager
音声合成SpeechSynthesizer (tts_v2 callback style)client.audio.tts.synthesize/stream/connect
テキスト埋め込みTextEmbedding.call / BatchTextEmbeddingclient.embeddings.create / client.embeddings.jobs.*
RerankTextReRank.callclient.rerank.create
エージェントアプリケーションApplication.callclient.apps.completions.create
ファイル管理Files.upload/list/get/deleteclient.files.upload/list/get/delete
モデル一覧Models.list/getclient.models.list/get

クライアントの構築と認証

1.x はモジュールレベルのグローバル変数で設定します。2.0 は Client コンストラクターの引数で設定します(優先順位: コンストラクター > dashscope.settings > 環境変数 > ~/.dashscope/config.toml)。
# 1.x: globals
import dashscope
dashscope.api_key = os.getenv("DASHSCOPE_API_KEY")
dashscope.base_http_api_url = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1"
# 2.0: client construction
import dashscope
client = dashscope.Client(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="cn-beijing",
)

テキスト生成

# 1.x
from dashscope import Generation
response = Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-plus",
    messages=messages,
    result_format="message",
)
if response.status_code == 200:
    print(response.output.choices[0].message.content)
else:
    print(f"HTTP status: {response.status_code}")
    print(f"Error code: {response.code}")
    print(f"Error message: {response.message}")
# 2.0
from dashscope.v2 import DashScopeError
try:
    response = client.chat.completions.create(
        model="qwen-plus",
        messages=messages,
    )
    print(response.choices[0].message.content)
except DashScopeError as e:
    print(f"HTTP status: {e.status_code}")
    print(f"Error code: {e.code}")
    print(f"Error message: {e.message}")

マルチモーダル対話

# 1.x
from dashscope import MultiModalConversation
response = MultiModalConversation.call(
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model='qwen3-vl-plus',
    messages=[{
        "role": "user",
        "content": [
            {"image": "https://example.com/image.png"},
            {"text": "What is in this picture?"},
        ],
    }])
print(response.output.choices[0].message.content[0]['text'])
# 2.0: content parts shape kept, flat access
response = client.multimodal.chat.create(
    model='qwen3-vl-plus',
    messages=[{
        "role": "user",
        "content": [
            {"image": "https://example.com/image.png"},
            {"text": "What is in this picture?"},
        ],
    }])
print(response.output_text)

画像生成

# 1.x: synchronous call (blocks until done)
from dashscope import ImageSynthesis
rsp = ImageSynthesis.call(api_key=os.getenv("DASHSCOPE_API_KEY"),
                          model=ImageSynthesis.Models.wanx_v1,
                          prompt=prompt,
                          n=1,
                          style='<watercolor>',
                          size='1024*1024')
if rsp.status_code == HTTPStatus.OK:
    for result in rsp.output.results:
        print(result.url)
else:
    print('Failed, status_code: %s, code: %s, message: %s' %
          (rsp.status_code, rsp.code, rsp.message))
# 2.0: generate one-shot (submit and wait); enum classes become strings
job = client.images.generate(
    model="wanx2.1-t2i-turbo",
    prompt=prompt,
    n=1,
    size='1024*1024',
)
for url in job.image_urls:
    print(url)
ステップ実行のタスク(1.x の async_call/fetch/wait)は client.images.jobs.create/fetch/wait に対応します。タスクの状態判定は rsp.output.task_status == 'SUCCEEDED' から job.succeeded に変わります。

動画生成

# 1.x
from dashscope import VideoSynthesis
rsp = VideoSynthesis.call(api_key=api_key,
                          model='wan3.0-video',
                          prompt=prompt,
                          resolution="720P",
                          ratio="16:9",
                          duration=15,
                          watermark=True)
if rsp.status_code == HTTPStatus.OK:
    print("video_url:", rsp.output.video_url)
# 2.0
job = client.videos.generate(
    model='wan3.0-video',
    prompt=prompt,
    resolution="720P",
    ratio="16:9",
    duration=15,
    watermark=True,
)
print("video_url:", job.video_url)
1.x の VideoSynthesis では extend_prompt のデフォルトは True です。2.0 では prompt_extend となり、デフォルトはサーバー側で決定されます。旧デフォルトに依存していた呼び出しでは prompt_extend=True を明示的に渡す必要があります。

音声ファイルの文字起こし

# 1.x: async_call submit + wait
from dashscope.audio.asr import Transcription
task_response = Transcription.async_call(
    model='paraformer-v2',
    file_urls=['{YOUR_AUDIO_URL}'],
    language_hints=['zh', 'en'],
)
transcribe_response = Transcription.wait(task=task_response.output.task_id)
if transcribe_response.status_code == HTTPStatus.OK:
    print(json.dumps(transcribe_response.output, indent=4, ensure_ascii=False))
# 2.0: transcribe one-shot; non-signature parameters go via parameters
job = client.audio.asr.transcribe(
    ['{YOUR_AUDIO_URL}'],
    model='paraformer-v2',
    parameters={'language_hints': ['zh', 'en']},
)
print(json.dumps(job.model_dump(), indent=4, ensure_ascii=False))
ステップごとの制御(旧 async_call + fetch ループ)は、client.audio.asr.jobs.create + jobs.fetch ループに対応します。

リアルタイム音声認識

1.x はコールバッククラス(Recognition + RecognitionCallback)を使用します。2.0 ではコンテキストマネージャー + イベントの反復処理を使用します。
# 1.x (callback style, excerpt)
from dashscope.audio.asr import Recognition
class Callback(RecognitionCallback):
    def on_result(self, result): ...
recognition = Recognition(model='paraformer-realtime-v2', callback=Callback())
recognition.start()
recognition.send_audio_frame(chunk)
recognition.stop()
# 2.0 (event iteration, send and receive concurrently)
from concurrent.futures import ThreadPoolExecutor

def receive_events(rec):
    for event in rec.events():
        print(event)

with client.audio.asr.recognize(
        model='paraformer-realtime-v2',
        format='pcm',
        sample_rate=16000,
) as recognition:
    with ThreadPoolExecutor(max_workers=1) as pool:
        receiver = pool.submit(receive_events, recognition)
        for chunk in iter_pcm_chunks():  # real-time PCM frames provided by the application
            recognition.send_audio_frame(chunk)
        recognition.stop()
        receiver.result()
ローカルファイルの一括認識(1.x の Recognition.call(file))は、for event in client.audio.asr.recognize_file(path, model=...): に対応します。

音声合成

1.x の tts_v2 はコールバックで音声を受け取ります。2.0 では反復処理/セッション形式を使用します。
# 1.x (callback style, excerpt)
from dashscope.audio.tts_v2 import SpeechSynthesizer, ResultCallback
class Callback(ResultCallback):
    def on_data(self, data: bytes): audio.write(data)
synthesizer = SpeechSynthesizer(
    model="cosyvoice-v3-flash",
    voice="longanyang",
    callback=Callback(),
)
synthesizer.streaming_call(text)
synthesizer.streaming_complete()
# 2.0: connect session (segmented input + segmented audio)
with client.audio.tts.connect(
        model="cosyvoice-v3-flash",
        voice="longanyang",
        format="mp3",
) as session:
    session.send_text(text)
    session.flush()
    session.stop()  # End the task and wait for remaining audio
    for chunk in session.audio_chunks():
        audio.write(chunk)
一括合成には client.audio.tts.synthesize(text, model=..., voice=...) を使用します。純粋なストリーミングでは client.audio.tts.stream(text, ...) を反復処理します。

埋め込みとリランキング

# 1.x
resp = dashscope.TextEmbedding.call(
    model="qwen3.7-text-embedding",
    input="The quality of this clothing is excellent.",
)
if resp.status_code == HTTPStatus.OK:
    print(resp)
# 2.0
resp = client.embeddings.create(
    model="qwen3.7-text-embedding",
    input="The quality of this clothing is excellent.",
)
for item in resp.embeddings:
    print(item.index, len(item.embedding))
バッチ埋め込み(1.x の BatchTextEmbedding)は client.embeddings.jobs.create/fetch/wait に対応します。リランキングの TextReRank.call は client.rerank.create に対応し、結果の取得は resp.output.results[i] から resp.results[i] に変わります。

エージェントアプリケーションの呼び出し

# 1.x
from dashscope import Application
response = Application.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    app_id='APP_ID',
    prompt='Who are you?')
if response.status_code != HTTPStatus.OK:
    print(f'code={response.status_code}, message={response.message}')
else:
    print(response.output.text)
# 2.0
from dashscope.v2 import DashScopeError
try:
    response = client.apps.completions.create(
        app_id='APP_ID',
        prompt='Who are you?')
    print(response.text)
except DashScopeError as e:
    print(f'code={e.code}, message={e.message}')
アプリケーションのストリーミング呼び出しでは incremental_output パラメーターが維持されます(フレームの形式を決定します)。フレームごとの出力は response.output.text から partial.text に変わります。

動作上の相違点

移行時に注意すべき動作上の相違点は、インターフェース名以外に以下のとおりです。
  • エラー処理: 1.x ではレスポンス上の status_code/code を自查します。2.0 ではデフォルトで失敗時に DashScopeError 例外ファミリーを送出します(e.code/e.status_code/e.request_id/e.message を含む)。エンベロープ形式が必要な場合は Client(raise_on_error=False) を構築してください。
  • ストリーミング出力: 1.x の Generation.call(stream=True) はデフォルトで毎フレーム全文を再送します(増分には incremental_output=True)。2.0 のストリームは常に増分です。Model Studio アプリケーション(apps.completions)は incremental_output スイッチを維持します。
  • 非同期タスクの待機: 1.x の wait はデフォルトで無期限に待機し、タイムアウト時にエラーレスポンスを返します。2.0 の jobs.wait はデフォルトで合計 24 時間の予算と指数バックオフでのポーリングを行い、タスクが FAILED になると例外を送出します。
  • レスポンス構造: 1.x では業務内容が output フィールドの下にラップされます(response.output.choices[...])。2.0 ではフラット化されており(response.choices[...])、resp.output_text や job.succeeded などの簡易アクセスが追加されています。
  • シグネチャ外パラメーター: 2.0 の各リソースメソッドは閉じた名前付きシグネチャを持ちます。1.x で透過的に渡していたモデル固有のパラメーターは parameters={...} 経由に変更が必要です(画像素材系は extra_input=)。

関連ドキュメント