すべてのプロダクト
Search
ドキュメントセンター

Alibaba Cloud Model Studio:オムニモーダル (Qwen-Omni)

最終更新日:Nov 20, 2025

Qwen-Omni モデルは、テキストと、画像、音声、ビデオなどの単一の他のモダリティの組み合わせを入力として受け入れ、テキストまたは音声で応答を生成します。人間のようなさまざまな音声を提供し、複数の言語や方言での音声出力をサポートしています。テキスト作成、視覚認識、音声アシスタントなどのシナリオで使用できます。

使用開始

前提条件

呼び出しメソッド: Qwen-Omni は現在、ストリーミング出力のみをサポートしています。stream パラメーターは True に設定する必要があります。そうしないと、エラーが発生します。

次の例は、Qwen-Omni API にテキストを送信し、テキストと音声を含むストリーミング応答を受信する方法を示しています。

import os
import base64
import soundfile as sf
import numpy as np
from openai import OpenAI

# 1. クライアントを初期化します
client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),  # 環境変数が構成されていることを確認してください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

# 2. リクエストを開始します
try:
    completion = client.chat.completions.create(
        model="qwen3-omni-flash",
        messages=[{"role": "user", "content": "Who are you"}],
        modalities=["text", "audio"],  # テキストと音声出力を指定します
        audio={"voice": "Cherry", "format": "wav"},
        stream=True,  # True に設定する必要があります
        stream_options={"include_usage": True},
    )

    # 3. ストリーミング応答を処理し、音声をデコードします
    print("Model response:")
    audio_base64_string = ""
    for chunk in completion:
        # テキスト部分を処理します
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="")

        # 音声部分を収集します
        if chunk.choices and hasattr(chunk.choices[0].delta, "audio") and chunk.choices[0].delta.audio:
            audio_base64_string += chunk.choices[0].delta.audio.get("data", "")

    # 4. 音声ファイルを保存します
    if audio_base64_string:
        wav_bytes = base64.b64decode(audio_base64_string)
        audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
        sf.write("audio_assistant.wav", audio_np, samplerate=24000)
        print("\nAudio file saved to: audio_assistant.wav")

except Exception as e:
    print(f"Request failed: {e}")
// 実行前の準備:
// Windows/Mac/Linux 共通:
// 1. Node.js がインストールされていることを確認します (バージョン >= 14 を推奨)
// 2. 次のコマンドを実行して、必要な依存関係をインストールします:
//    npm install openai wav

import OpenAI from "openai";
import { createWriteStream } from 'node:fs';
import { Writer } from 'wav';

// 音声変換関数を定義します: Base64 文字列を変換し、標準の WAV 音声ファイルとして保存します
async function convertAudio(audioString, audioPath) {
    try {
        // Base64 文字列をバッファーにデコードします
        const wavBuffer = Buffer.from(audioString, 'base64');
        // WAV ファイル書き込みストリームを作成します
        const writer = new Writer({
            sampleRate: 24000,  // サンプルレート
            channels: 1,        // シングルチャンネル
            bitDepth: 16        // 16 ビット深度
        });
        // 出力ファイルストリームを作成し、パイプライン接続を確立します
        const outputStream = createWriteStream(audioPath);
        writer.pipe(outputStream);

        // PCM データを書き込み、書き込みを終了します
        writer.write(wavBuffer);
        writer.end();

        // Promise を使用して、ファイルが書き込まれるのを待ちます
        await new Promise((resolve, reject) => {
            outputStream.on('finish', resolve);
            outputStream.on('error', reject);
        });

        // 音声の完全性を確保するために、余分な待機時間を追加します
        await new Promise(resolve => setTimeout(resolve, 800));

        console.log(`\nAudio file successfully saved as ${audioPath}`);
    } catch (error) {
        console.error('An error occurred during processing:', error);
    }
}

//  1. クライアントを初期化します
const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
// 2. リクエストを開始します
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash",  
    messages: [
        {
            "role": "user",
            "content": "Who are you?"
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

let audioString = "";
console.log("Model response:")

// 3. ストリーミング応答を処理し、音声をデコードします
for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        // テキストコンテンツを処理します
        if (chunk.choices[0].delta.content) {
            process.stdout.write(chunk.choices[0].delta.content);
        }
        // 音声コンテンツを処理します
        if (chunk.choices[0].delta.audio) {
            if (chunk.choices[0].delta.audio["data"]) {
                audioString += chunk.choices[0].delta.audio["data"];
            }
        }
    }
}
// 4. 音声ファイルを保存します
convertAudio(audioString, "audio_assistant.wav");
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-omni-flash",
    "messages": [
        {
            "role": "user", 
            "content": "Who are you?"
        }
    ],
    "stream":true,
    "stream_options":{
        "include_usage":true
    },
    "modalities":["text","audio"],
    "audio":{"voice":"Cherry","format":"wav"}
}'

応答

Python および Node.js コードを実行すると、モデルのテキスト応答がコンソールに表示されます。コードファイルと同じディレクトリに audio_assistant.wav という名前の音声ファイルが生成されます。

Model response:
I am a large language model developed by Alibaba Cloud. My name is Qwen. How can I help you?

HTTP コードを直接実行すると、テキスト、および Base64 でエンコードされたオーディオデータを含む audio フィールドが返されます。

data: {"choices":[{"delta":{"content":"I"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
data: {"choices":[{"delta":{"content":" am"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
......
data: {"choices":[{"delta":{"audio":{"data":"/v8AAAAAAAAAAAAAAA...","expires_at":1757647879,"id":"audio_a68eca3b-c67e-4666-a72f-73c0b4919860"}},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757647879,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-a68eca3b-c67e-4666-a72f-73c0b4919860"}
data: {"choices":[{"finish_reason":"stop","delta":{"audio":{"transcript":""}},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757940330,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-9cdd5a26-f9e9-4eff-9dcc-93a878165afc"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":207,"completion_tokens":103,"total_tokens":310,"completion_tokens_details":{"audio_tokens":83,"text_tokens":20},"prompt_tokens_details":{"text_tokens":207}},"created":1757940330,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-9cdd5a26-f9e9-4eff-9dcc-93a878165afc"}

モデルリスト

Qwen-VL モデルと比較して、Qwen-Omni モデルは次のことができます:

  • ビデオファイル内の視覚情報と音声情報を理解する。

  • 複数のモダリティのデータを理解する。

  • 音声を出力する。

また、視覚と音声の理解においても優れたパフォーマンスを発揮します。

最高のパフォーマンスを得るには、Qwen3-Omni-Flash を使用してください。Qwen-Omni-Turbo (更新終了) と比較して、Qwen3-Omni-Flash は大幅な改善を提供します:

  • 思考モードと非思考モードの両方をサポートします。 enable_thinking パラメーターを使用してモードを切り替えることができます。デフォルトでは、思考モードは無効になっています。

  • 非思考モードでの音声出力の場合:

    • サポートされる音声の数が 17 に増加しました。Qwen-Omni-Turbo は 4 つしかサポートしていません。

    • サポートされる言語の数が 10 に増加しました。Qwen-Omni-Turbo は 2 つしかサポートしていません。

海外 (シンガポール)

商用モデル

オープンソース版と比較して、商用モデルは最新の機能と改善を提供します。

モデル

バージョン

モード

コンテキストウィンドウ

最大入力

最大思考連鎖

最大出力

無料クォータ

(注)

(トークン)

qwen3-omni-flash

現在、qwen3-omni-flash-2025-09-15 と同じ機能を持ちます

安定

思考モード

65,536

16,384

32,768

16,384

それぞれ 100 万トークン (モダリティに依存しない)

Model Studio を有効化してから 90 日間有効

非思考モード

49,152

-

qwen3-omni-flash-2025-09-15

qwen3-omni-flash-0915 とも呼ばれます

スナップショット

思考モード

65,536

16,384

32,768

16,384

非思考モード

49,152

-

その他のモデル

モデル

バージョン

コンテキストウィンドウ

最大入力

最大出力

無料クォータ

(注)

(トークン)

qwen-omni-turbo

このバージョンは qwen-omni-turbo-2025-03-26 と同じ機能を持ちます。

安定

32,768

30,720

2,048

それぞれ 100 万トークン (モダリティに依存しない)

Model Studio を有効化してから 90 日間有効です。

qwen-omni-turbo-latest

常に最新のスナップショットバージョンを指します。
同等の機能

最新

qwen-omni-turbo-2025-03-26

qwen-omni-turbo-0326 とも呼ばれます。

スナップショット

オープンソースモデル

モデル

コンテキストウィンドウ

最大入力

最大出力

無料クォータ

(注)

(トークン)

qwen2.5-omni-7b

32,768

30,720

2,048

100 万トークン (モダリティに関係なく)

Alibaba Cloud Model Studio を有効化してから 90 日間有効です。

中国本土 (北京)

商用モデル

モデル

バージョン

モード

コンテキストウィンドウ

最大入力

最大思考連鎖

最大出力

無料クォータ

(注)

(トークン)

qwen3-omni-flash

現在、qwen3-omni-flash-2025-09-15 と同じ機能を持ちます

安定

思考モード

65,536

16,384

32,768

16,384

無料クォータなし

非思考モード

49,152

-

qwen3-omni-flash-2025-09-15

qwen3-omni-flash-0915 とも呼ばれます

スナップショット

思考モード

65,536

16,384

32,768

16,384

非思考モード

49,152

-

その他のモデル

モデル

バージョン

コンテキストウィンドウ

最大入力

最大出力

無料クォータ

(注)

(トークン)

qwen-omni-turbo

このモデルは現在、qwen-omni-turbo-2025-03-26 と同じ機能を持ちます。

安定

32,768

30,720

2,048

無料クォータなし

qwen-omni-turbo-latest

常に最新のスナップショットと一致
同一の機能

最新

qwen-omni-turbo-2025-03-26

qwen-omni-turbo-0326 とも呼ばれます。

スナップショット

qwen-omni-turbo-2025-01-19

qwen-omni-turbo-0119 とも呼ばれます。

オープンソースモデル

モデル

コンテキストウィンドウ

最大入力

最大出力

無料クォータ

(注)

(トークン)

qwen2.5-omni-7b

32,768

30,720

2,048

無料クォータなし

使用上の注意

入力

単一の user メッセージでは、content 配列にテキストと、画像、音声、ビデオなどの他のモダリティを 1 つだけ含めることができます。複数の他のモダリティを含めることはできません。

出力

  • サポートされている出力モダリティ: 音声出力は Base64 でエンコードされたデータです。音声ファイルに変換する方法の詳細については、「Base64 でエンコードされた音声データ出力の解析」をご参照ください。

    出力モダリティ

    modalities パラメーター値

    応答スタイル

    テキスト

    ["text"] (デフォルト)

    よりフォーマルで書き言葉のスタイル。

    テキストと音声

    ["text","audio"]

    Qwen3-Omni-Flash は思考モードでの音声出力をサポートしていません。

    より会話的。応答にはフィラーワードが含まれ、さらなる対話を促します。

    Qwen-Omni-Turbo は、出力モダリティに音声が含まれる場合、システムメッセージの設定をサポートしていません。
  • サポートされている音声出力言語:

    • Qwen-Omni-Turbo: 中国語 (標準語) と英語のみをサポートします。

    • Qwen3-Omni-Flash (非思考モード): 中国語 (標準語および一部の方言)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語をサポートします。

  • サポートされている音声: audio パラメーターを使用して、音声出力の音声とファイル形式を構成できます。例: audio={"voice": "Cherry", "format": "wav"}:

    • ファイル形式 (format): "wav" にのみ設定できます。

    • 音声 (voice): 各モデルがサポートする音声のリストについては、「音声リスト」をご参照ください。

制限事項

  • ストリーミング出力は必須です: Qwen-Omni モデルへのすべてのリクエストは stream=True を設定する必要があります。

  • Qwen3-Omni-Flash モデルのみがハイブリッド思考モデルです。呼び出し方法については、「思考モードの有効化または無効化」をご参照ください。思考モードでは、音声出力はサポートされていません。

思考モードの有効化または無効化

Qwen3-Omni-Flash モデルはハイブリッド思考モデルです。enable_thinking パラメーターを使用して、思考モードを有効または無効にできます:

  • true: 思考モードを有効にします。

  • false (default): 思考モードを無効にします。

Qwen-Omni-Turbo は思考モデルではありません。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash",
    messages=[{"role": "user", "content": "Who are you"}],

    # 思考モードを有効または無効にします。思考モードでは音声出力はサポートされていません。qwen-omni-turbo は enable_thinking の設定をサポートしていません。
    extra_body={'enable_thinking': True},

    # 出力データモダリティを設定します。現在、非思考モードでは ["text","audio"] と ["text"] の 2 つがサポートされています。思考モードでは ["text"] のみがサポートされています。
    modalities=["text"],

    # 音声を設定します。思考モードでは audio パラメーターはサポートされていません。
    # audio={"voice": "Cherry", "format": "wav"},
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash",
    messages: [
        { role: "user", content: "Who are you?" }
    ],

    // エラーを回避するには、stream を True に設定する必要があります。
    stream: true,
    stream_options: {
        include_usage: true
    },
    // 思考モードを有効または無効にします。思考モードでは音声出力はサポートされていません。qwen-omni-turbo は enable_thinking の設定をサポートしていません。
    extra_body:{'enable_thinking': true},
    //  出力データモダリティを設定します。現在、非思考モードでは ["text","audio"] と ["text"] の 2 つがサポートされています。思考モードでは ["text"] のみがサポートされています。
    modalities: ["text"],
    // 音声を設定します。思考モードでは audio パラメーターはサポートされていません。
    //audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3-omni-flash",
    "messages": [
        {
            "role": "user",
            "content": "Who are you?"
        }
    ],
    "stream":true,
    "stream_options":{
        "include_usage":true
    },
    "modalities":["text"],
    "enable_thinking": true
}'

応答

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"finish_reason":null,"logprobs":null,"delta":{"content":null,"reasoning_content":"hmm"},"index":0}],"object":"chat.completion.chunk","usage":null,"reated":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"delta":{"content":null,"reasoning_content":","},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"reated":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
......
data: {"choices":[{"delta":{"content":"tell me"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"tem_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"delta":{"content":"!"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"systm_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":11,"completion_tokens":363,"total_tokens":374,"completion_tokens_details":{"reasoning_tokens":195,"text_tokens":168},"prompt_tokens_details":{"text_tokens":11}},"created":1757937336,"system_fingerprint":null,"model":"qwen3-omni-flash","id":"chatcmpl-ce3d6fe5-e717-4b7e-8b40-3aef12288d4c"}

画像とテキストの入力

Qwen-Omni は複数の画像入力をサポートしています。入力画像の要件は次のとおりです:

  • 単一の画像ファイルのサイズは 10 MB を超えることはできません。

  • 画像の数は、モデルの画像とテキストの合計トークン制限によって制限されます。すべての画像の合計トークン数は、モデルの最大入力トークン制限を超えてはなりません。

  • 画像の幅と高さは両方とも 10 ピクセルより大きくなければなりません。縦横比は 200:1 または 1:200 を超えてはなりません。

  • サポートされている画像の種類については、「視覚理解」をご参照ください。

次のサンプルコードは、インターネットからの画像 URL を例として使用しています。ローカル画像を入力するには、「Base64 でエンコードされたローカルファイルの入力」をご参照ください。現在、ストリーミング出力での呼び出しのみがサポートされています。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
                    },
                },
                {"type": "text", "text": "What scene is depicted in the image?"},
            ],
        },
    ],
    # 出力データモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={
        "include_usage": True
    }
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "image_url",
                "image_url": { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg" },
            },
            { "type": "text", "text": "What scene is depicted in the image?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===


curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen2.5-omni-7b",
    "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "image_url",
          "image_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"
          }
        },
        {
          "type": "text",
          "text": "What scene is depicted in the image?"
        }
      ]
    }
  ],
    "stream":true,
    "stream_options":{
        "include_usage":true
    },
    "modalities":["text","audio"],
    "audio":{"voice":"Cherry","format":"wav"}
}'

音声とテキストの入力

  • 入力できる音声ファイルは 1 つだけです。

  • ファイルサイズ

    • Qwen3-Omni-Flash: 100 MB を超えることはできず、最大持続時間は 20 分です。

    • Qwen-Omni-Turbo: 10 MB を超えることはできず、最大持続時間は 3 分です。

次のサンプルコードは、インターネットからの音声 URL を例として使用しています。ローカル音声ファイルを入力するには、「Base64 でエンコードされたローカルファイルの入力」をご参照ください。現在、ストリーミング出力での呼び出しのみがサポートされています。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash",# モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {
                        "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
                        "format": "wav",
                    },
                },
                {"type": "text", "text": "What is this audio about"},
            ],
        },
    ],
    # 出力データモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "input_audio",
                "input_audio": { "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav", "format": "wav" },
            },
            { "type": "text", "text": "What is this audio about" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen2.5-omni-7b",
    "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "input_audio",
          "input_audio": {
            "data": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20250211/tixcef/cherry.wav",
            "format": "wav"
          }
        },
        {
          "type": "text",
          "text": "What is this audio about"
        }
      ]
    }
  ],
    "stream":true,
    "stream_options":{
        "include_usage":true
    },
    "modalities":["text","audio"],
    "audio":{"voice":"Cherry","format":"wav"}
}'

ビデオとテキストの入力

ビデオは画像リストとして、またはビデオファイル (音声理解付き)として入力できます。

次のサンプルコードは、インターネットからのビデオ URL を例として使用しています。ローカルビデオを入力するには、「Base64 でエンコードされたローカルファイルの入力」をご参照ください。現在、ストリーミング出力での呼び出しのみがサポートされています。

画像リスト形式

画像の数

  • Qwen3-Omni-Flash: 最小 2 枚、最大 128 枚の画像。

  • Qwen-Omni-Turbo: 最小 4 枚、最大 80 枚の画像。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg",
                    ],
                },
                {"type": "text", "text": "Describe the process shown in this video"},
            ],
        }
    ],
    # 出力データモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", //モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [{
        role: "user",
        content: [
            {
                type: "video",
                video: [
                    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
                    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
                    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
                    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
                ]
            },
            {
                type: "text",
                text: "Describe the process shown in this video"
            }
        ]
    }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen2.5-omni-7b",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
                    ]
                },
                {
                    "type": "text",
                    "text": "Describe the process shown in this video"
                }
            ]
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "modalities": ["text", "audio"],
    "audio": {
        "voice": "Cherry",
        "format": "wav"
    }
}'

ビデオファイル形式 (ビデオ内の音声を理解可能)

  • 入力できるビデオファイルは 1 つだけです。

  • ファイルサイズ:

    • Qwen3-Omni-Flash: 256 MB に制限され、持続時間は 150 秒に制限されます。

    • Qwen-Omni-Turbo: 150 MB に制限され、持続時間は 40 秒に制限されます。

  • ビデオファイル内の視覚情報と音声情報は別々に課金されます。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video_url",
                    "video_url": {
                        "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
                    },
                },
                {"type": "text", "text": "What is the content of the video?"},
            ],
        },
    ],
    # 出力データモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "video_url",
                "video_url": { "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4" },
            },
            { "type": "text", "text": "What is the content of the video?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});


for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen2.5-omni-7b",
    "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "video_url",
          "video_url": {
            "url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241115/cqqkru/1.mp4"
          }
        },
        {
          "type": "text",
          "text": "What is the content of the video"
        }
      ]
    }
  ],
    "stream":true,
    "stream_options": {
        "include_usage": true
    },
    "modalities":["text","audio"],
    "audio":{"voice":"Cherry","format":"wav"}
}'

マルチターン対話

Qwen-Omni のマルチターン対話機能を使用する場合、次の点に注意してください:

  • アシスタントメッセージ

    messages 配列のアシスタントメッセージは、テキストデータのみをサポートします。

  • ユーザーメッセージ

    ユーザーメッセージには、テキストと他の 1 つのモダリティのデータのみを含めることができます。マルチターン対話では、別々のユーザーメッセージで異なるモダリティを使用できます。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {
                        "data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",
                        "format": "mp3",
                    },
                },
                {"type": "text", "text": "What is this audio about"},
            ],
        },
        {
            "role": "assistant",
            "content": [{"type": "text", "text": "This audio says: Welcome to Alibaba Cloud"}],
        },
        {
            "role": "user",
            "content": [{"type": "text", "text": "Can you tell me about this company?"}],
        },
    ],
    # 出力データモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text"],
    # エラーを回避するには、stream を True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {
                        "data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3",
                        "format": "mp3",
                    },
                },
                { "type": "text", "text": "What is this audio about" },
            ],
        },
        {
            "role": "assistant",
            "content": [{ "type": "text", "text": "This audio says: Welcome to Alibaba Cloud" }],
        },
        {
            "role": "user",
            "content": [{ "type": "text", "text": "Can you tell me about this company?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text"]
});


for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}
# ======= 重要事項 =======
# シンガポールリージョンと北京リージョンでは API キーが異なります。詳細については、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください
# 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions に置き換えてください
# === 実行前にこのコメントを削除してください ===

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen2.5-omni-7b",
  "messages": [
    {
      "role": "user",
      "content": [
        {
          "type": "input_audio",
          "input_audio": {
            "data": "https://dashscope.oss-cn-beijing.aliyuncs.com/audios/welcome.mp3"
          }
        },
        {
          "type": "text",
          "text": "What is this audio about"
        }
      ]
    },
    {
      "role": "assistant",
      "content": [
        {
          "type": "text",
          "text": "This audio says: Welcome to Alibaba Cloud"
        }
      ]
    },
    {
      "role": "user",
      "content": [
        {
          "type": "text",
          "text": "Can you tell me about this company?"
        }
      ]
    }
  ],
  "stream": true,
  "stream_options": {
    "include_usage": true
  },
  "modalities": ["text"]
}'

Base64 でエンコードされたオーディオデータ出力の解析

Qwen-Omni からのオーディオ出力は、ストリームで配信される Base64 でエンコードされたデータです。オーディオファイルを再構築するには、文字列変数を使用して、各フラグメントが到着するたびに Base64 データを蓄積できます。ストリームが完了したら、最終的な文字列をデコードしてオーディオファイルを作成できます。または、各フラグメントを受信するたびにリアルタイムでデコードして再生することもできます。

# pyaudio のインストール手順:
# APPLE Mac OS X
#   brew install portaudio
#   pip install pyaudio
# Debian/Ubuntu
#   sudo apt-get install python-pyaudio python3-pyaudio
#   or
#   pip install pyaudio
# CentOS
#   sudo yum install -y portaudio portaudio-devel && pip install pyaudio
# Microsoft Windows
#   python -m pip install pyaudio

import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf

client = OpenAI(
    # シンガポールリージョンと北京リージョンの API キーは異なります。詳細については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages=[{"role": "user", "content": "Who are you"}],
    # 出力データのモダリティを設定します。現在サポートされているのは ["text","audio"] と ["text"] の 2 つです。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # エラーを避けるために stream は True に設定する必要があります。
    stream=True,
    stream_options={"include_usage": True},
)

# 方法 1: 生成完了後にデコード
audio_string = ""
for chunk in completion:
    if chunk.choices:
        if hasattr(chunk.choices[0].delta, "audio"):
            try:
                audio_string += chunk.choices[0].delta.audio["data"]
            except Exception as e:
                print(chunk.choices[0].delta.audio["transcript"])
    else:
        print(chunk.usage)

wav_bytes = base64.b64decode(audio_string)
audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
sf.write("audio_assistant_py.wav", audio_np, samplerate=24000)

# 方法 2: 生成中にデコード (方法 2 を使用するには、方法 1 のコードをコメントアウトします)
# # PyAudio を初期化
# import pyaudio
# import time
# p = pyaudio.PyAudio()
# # オーディオストリームを作成
# stream = p.open(format=pyaudio.paInt16,
#                 channels=1,
#                 rate=24000,
#                 output=True)

# for chunk in completion:
#     if chunk.choices:
#         if hasattr(chunk.choices[0].delta, "audio"):
#             try:
#                 audio_string = chunk.choices[0].delta.audio["data"]
#                 wav_bytes = base64.b64decode(audio_string)
#                 audio_np = np.frombuffer(wav_bytes, dtype=np.int16)
#                 # オーディオデータを直接再生
#                 stream.write(audio_np.tobytes())
#             except Exception as e:
#                 print(chunk.choices[0].delta.audio["transcript"])

# time.sleep(0.8)
# # リソースをクリーンアップ
# stream.stop_stream()
# stream.close()
# p.terminate()
// 実行前の準備:
// Windows/Mac/Linux 共通:
// 1. Node.js がインストールされていることを確認します (バージョン 14 以上を推奨)
// 2. 次のコマンドを実行して、必要な依存関係をインストールします:
//    npm install openai wav
// 
// リアルタイム再生機能 (方法 2) を使用するには、以下も必要です:
// Windows:
//    npm install speaker
// Mac:
//    brew install portaudio
//    npm install speaker
// Linux (Ubuntu/Debian):
//    sudo apt-get install libasound2-dev
//    npm install speaker

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンの API キーは異なります。詳細については、「https://www.alibabacloud.com/help/en/model-studio/get-api-key」をご参照ください。
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下はシンガポールリージョンの URL です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // モデルが Qwen3-Omni-Flash の場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": "Who are you?"
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

// 方法 1: 生成完了後にデコード
// インストールが必要: npm install wav
import { createWriteStream } from 'node:fs';  // node:fs は Node.js の組み込みモジュールであり、インストールは不要です
import { Writer } from 'wav';

async function convertAudio(audioString, audioPath) {
    try {
        // Base64 文字列をバッファーにデコードします
        const wavBuffer = Buffer.from(audioString, 'base64');
        // WAV ファイル書き込みストリームを作成します
        const writer = new Writer({
            sampleRate: 24000,  // サンプルレート
            channels: 1,        // シングルチャンネル
            bitDepth: 16        // 16 ビット深度
        });
        // 出力ファイルストリームを作成し、パイプライン接続を確立します
        const outputStream = createWriteStream(audioPath);
        writer.pipe(outputStream);

        // PCM データを書き込み、書き込みを終了します
        writer.write(wavBuffer);
        writer.end();

        // Promise を使用してファイルの書き込みを待ちます
        await new Promise((resolve, reject) => {
            outputStream.on('finish', resolve);
            outputStream.on('error', reject);
        });

        // オーディオの完全性を確保するために、追加の待機時間を追加します
        await new Promise(resolve => setTimeout(resolve, 800));

        console.log(`Audio file successfully saved as ${audioPath}`);
    } catch (error) {
        console.error('An error occurred during processing:', error);
    }
}

let audioString = "";
for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        if (chunk.choices[0].delta.audio) {
            if (chunk.choices[0].delta.audio["data"]) {
                audioString += chunk.choices[0].delta.audio["data"];
            }
        }
    } else {
        console.log(chunk.usage);
    }
}
// 変換を実行します
convertAudio(audioString, "audio_assistant_mjs.wav");


// 方法 2: リアルタイムで生成して再生
// 上記のシステムの指示に従って、まず必要なコンポーネントをインストールする必要があります。
// import Speaker from 'speaker'; // オーディオ再生ライブラリをインポート

// // スピーカーインスタンスを作成 (構成は WAV ファイルパラメーターと一致)
// const speaker = new Speaker({
//     sampleRate: 24000,  // サンプルレート
//     channels: 1,        // サウンドチャンネル数
//     bitDepth: 16,       // ビット深度
//     signed: true        // 符号付き PCM
// });
// for await (const chunk of completion) {
//     if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
//         if (chunk.choices[0].delta.audio) {
//             if (chunk.choices[0].delta.audio["data"]) {
//                 const pcmBuffer = Buffer.from(chunk.choices[0].delta.audio.data, 'base64');
//                 // 再生のためにスピーカーに直接書き込みます
//                 speaker.write(pcmBuffer);
//             }
//         }
//     } else {
//         console.log(chunk.usage);
//     }
// }
// speaker.on('finish', () => console.log('Playback complete'));
// speaker.end(); // API ストリームの実際の終了に基づいて呼び出します

Base64 エンコードされたローカルファイルの入力

イメージ

この例では、ローカルに保存されたファイル eagle.png を使用します。

import os
from openai import OpenAI
import base64

client = OpenAI(
    # シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)


# Base64 エンコード形式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


base64_image = encode_image("eagle.png")

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "image_url",
                    "image_url": {"url": f"data:image/png;base64,{base64_image}"},
                },
                {"type": "text", "text": "このイメージは何のシーンを描いていますか?"},
            ],
        },
    ],
    # 出力モダリティを設定します。サポートされているモダリティは ["text", "audio"] と ["text"] です。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # stream を True に設定します。そうしないと、エラーが発生します。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

const encodeImage = (imagePath) => {
    const imageFile = readFileSync(imagePath);
    return imageFile.toString('base64');
};
const base64Image = encodeImage("eagle.png")

const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash",// Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "image_url",
                "image_url": { "url": `data:image/png;base64,${base64Image}` },
            },
            { "type": "text", "text": "このイメージは何のシーンを描いていますか?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}

オーディオ

この例では、ローカルに保存されたファイル welcome.mp3 を使用します。

import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf
import requests

client = OpenAI(
    # シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)


def encode_audio(audio_path):
    with open(audio_path, "rb") as audio_file:
        return base64.b64encode(audio_file.read()).decode("utf-8")


base64_audio = encode_audio("welcome.mp3")

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "input_audio",
                    "input_audio": {
                        "data": f"data:;base64,{base64_audio}",
                        "format": "mp3",
                    },
                },
                {"type": "text", "text": "このオーディオは何についてですか?"},
            ],
        },
    ],
    # 出力モダリティを設定します。サポートされているモダリティは ["text", "audio"] と ["text"] です。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # stream を True に設定します。そうしないと、エラーが発生します。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

const encodeAudio = (audioPath) => {
    const audioFile = readFileSync(audioPath);
    return audioFile.toString('base64');
};
const base64Audio = encodeAudio("welcome.mp3")

const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "input_audio",
                "input_audio": { "data": `data:;base64,${base64Audio}`, "format": "mp3" },
            },
            { "type": "text", "text": "このオーディオは何についてですか?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}

ビデオ

ビデオファイル

この例では、ローカルに保存されたファイル spring_mountain.mp4 を使用します。

import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf

client = OpenAI(
    # シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

# Base64 エンコード形式
def encode_video(video_path):
    with open(video_path, "rb") as video_file:
        return base64.b64encode(video_file.read()).decode("utf-8")


base64_video = encode_video("spring_mountain.mp4")

completion = client.chat.completions.create(
    model="qwen3-omni-falsh", # Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video_url",
                    "video_url": {"url": f"data:;base64,{base64_video}"},
                },
                {"type": "text", "text": "彼女は何を歌っていますか?"},
            ],
        },
    ],
    # 出力モダリティを設定します。サポートされているモダリティは ["text", "audio"] と ["text"] です。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # stream を True に設定します。そうしないと、エラーが発生します。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

const encodeVideo = (videoPath) => {
    const videoFile = readFileSync(videoPath);
    return videoFile.toString('base64');
};
const base64Video = encodeVideo("spring_mountain.mp4")

const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages: [
        {
            "role": "user",
            "content": [{
                "type": "video_url",
                "video_url": { "url": `data:;base64,${base64Video}` },
            },
            { "type": "text", "text": "彼女は何を歌っていますか?" }]
        }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }
}

イメージリスト

この例では、ローカルに保存されたファイル football1.jpgfootball2.jpgfootball3.jpg、および football4.jpg を使用します。

import os
from openai import OpenAI
import base64
import numpy as np
import soundfile as sf

client = OpenAI(
    # シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)


# Base64 エンコード形式
def encode_image(image_path):
    with open(image_path, "rb") as image_file:
        return base64.b64encode(image_file.read()).decode("utf-8")


base64_image_1 = encode_image("football1.jpg")
base64_image_2 = encode_image("football2.jpg")
base64_image_3 = encode_image("football3.jpg")
base64_image_4 = encode_image("football4.jpg")

completion = client.chat.completions.create(
    model="qwen3-omni-flash", # Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages=[
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        f"data:image/jpeg;base64,{base64_image_1}",
                        f"data:image/jpeg;base64,{base64_image_2}",
                        f"data:image/jpeg;base64,{base64_image_3}",
                        f"data:image/jpeg;base64,{base64_image_4}",
                    ],
                },
                {"type": "text", "text": "このビデオに示されている具体的な手順を説明してください。"},
            ],
        }
    ],
    # 出力モダリティを設定します。サポートされているモダリティは ["text", "audio"] と ["text"] です。
    modalities=["text", "audio"],
    audio={"voice": "Cherry", "format": "wav"},
    # stream を True に設定します。そうしないと、エラーが発生します。
    stream=True,
    stream_options={"include_usage": True},
)

for chunk in completion:
    if chunk.choices:
        print(chunk.choices[0].delta)
    else:
        print(chunk.usage)
import OpenAI from "openai";
import { readFileSync } from 'fs';

const openai = new OpenAI(
    {
        // シンガポールリージョンと北京リージョンの API キーは異なります。API キーを取得するには、https://www.alibabacloud.com/help/en/model-studio/get-api-key をご参照ください。
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 次の URL はシンガポールリージョン用です。北京リージョンのモデルを使用する場合は、URL を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);

const encodeImage = (imagePath) => {
    const imageFile = readFileSync(imagePath);
    return imageFile.toString('base64');
  };
const base64Image1 = encodeImage("football1.jpg")
const base64Image2 = encodeImage("football2.jpg")
const base64Image3 = encodeImage("football3.jpg")
const base64Image4 = encodeImage("football4.jpg")

const completion = await openai.chat.completions.create({
    model: "qwen3-omni-flash", // Qwen3-Omni-Flash モデルを使用する場合、非思考モードで実行します。
    messages: [{
        role: "user",
        content: [
            {
                type: "video",
                video: [
                    `data:image/jpeg;base64,${base64Image1}`,
                    `data:image/jpeg;base64,${base64Image2}`,
                    `data:image/jpeg;base64,${base64Image3}`,
                    `data:image/jpeg;base64,${base64Image4}`
                ]
            },
            {
                type: "text",
                text: "このビデオに示されている具体的な手順を説明してください。"
            }
        ]
    }],
    stream: true,
    stream_options: {
        include_usage: true
    },
    modalities: ["text", "audio"],
    audio: { voice: "Cherry", format: "wav" }
});

for await (const chunk of completion) {
    if (Array.isArray(chunk.choices) && chunk.choices.length > 0) {
        console.log(chunk.choices[0].delta);
    } else {
        console.log(chunk.usage);
    }

API リファレンス

Qwen-Omni の入力および出力パラメーターについては、「Qwen」をご参照ください。

課金およびレート制限

課金ルール

Qwen-Omni は、オーディオ、イメージ、ビデオなどのさまざまなモダリティのトークン数に基づいて課金されます。詳細については、「モデル一覧」をご参照ください。

オーディオ、イメージ、ビデオをトークンに変換するルール

オーディオ

Qwen-Omni-Turbo: 合計トークン = オーディオの長さ (秒) × 25。オーディオの長さが 1 秒未満の場合は、1 秒として計算されます。

イメージ

  • Qwen3-Omni-Flash モデル:32×32 ピクセルブロックが 1 トークンに相当します。

  • Qwen-Omni-Turbo モデル: 各 28×28 ピクセルブロックが 1 トークンに相当します。

イメージには、最小 4 トークン、最大 1280 トークンが必要です。次のコードを使用し、イメージのパスを指定することで、単一イメージの合計トークン数を見積もることができます。

import math
# Pillow ライブラリをインストールするには、次のコマンドを実行します: pip install Pillow
from PIL import Image

# Qwen-Omni-Turbo モデルの場合、factor を 28 に設定します。
# factor = 28
# Qwen3-Omni-Flash モデルの場合、factor を 32 に設定します。
factor = 32

def token_calculate(image_path=''):
    """
    param image_path: イメージのパス。
    return: 単一イメージのトークン数。
    """
    if len(image_path) > 0:
        # 指定されたイメージファイルを開きます。
        image = Image.open(image_path)
        # イメージの元のディメンションを取得します。
        height = image.height
        width = image.width
    print(f"Image dimensions before scaling: Height={height}, Width={width}")
    # 高さを factor の倍数に調整します。
    h_bar = round(height / factor) * factor
    # 幅を factor の倍数に調整します。
    w_bar = round(width / factor) * factor
    # イメージの最小トークン数: 4 トークン。
    min_pixels = 4 * factor * factor
    # イメージの最大トークン数: 1280 トークン。
    max_pixels = 1280 * factor * factor
    # 合計ピクセル数が [min_pixels, max_pixels] の範囲内になるようにイメージをスケーリングします。
    if h_bar * w_bar > max_pixels:
        # スケーリングされたイメージの合計ピクセル数が max_pixels を超えないように、ズーム係数 beta を計算します。
        beta = math.sqrt((height * width) / max_pixels)
        # 調整後の高さが factor の倍数になるように再計算します。
        h_bar = math.floor(height / beta / factor) * factor
        # 調整後の幅が factor の倍数になるように再計算します。
        w_bar = math.floor(width / beta / factor) * factor
    elif h_bar * w_bar < min_pixels:
        # スケーリングされたイメージの合計ピクセル数が min_pixels 未満にならないように、ズーム係数 beta を計算します。
        beta = math.sqrt(min_pixels / (height * width))
        # 調整後の高さが factor の倍数になるように再計算します。
        h_bar = math.ceil(height * beta / factor) * factor
        # 調整後の幅が factor の倍数になるように再計算します。
        w_bar = math.ceil(width * beta / factor) * factor
    print(f"Scaled image dimensions: Height={h_bar}, Width={w_bar}")
    # イメージのトークン数を計算します: 合計ピクセル数 / (factor * factor)。
    token = int((h_bar * w_bar) / (factor * factor)) + 2
    print(f"Number of tokens after scaling: {token}")
    return token
    
if __name__ == "__main__":
    token = token_calculate(image_path="path/to/your/test.jpg")

ビデオ

ビデオファイルのトークンは、video_tokens (ビジュアル) と audio_tokens (オーディオ) に分かれています。

  • video_tokens

    計算は複雑です。次のコードをご参照ください。

    # 使用する前に、opencv-python をインストールします: pip install opencv-python
    import math
    import os
    import logging
    import cv2
    
    logger = logging.getLogger(__name__)
    
    # 固定パラメーター
    FRAME_FACTOR = 2
    
    # Qwen3-Omni-Flash モデルの場合、IMAGE_FACTOR を 32 に設定します。
    IMAGE_FACTOR = 32
    
    # Qwen-Omni-Turbo モデルの場合、IMAGE_FACTOR を 28 に設定します。
    # IMAGE_FACTOR = 28
    
    # ビデオフレームの縦横比
    MAX_RATIO = 200
    
    # ビデオフレームの最小トークン数。Qwen3-Omni-Flash の場合: 128 * 32 * 32
    VIDEO_MIN_PIXELS = 128 * 32 * 32
    # Qwen-Omni-Turbo の場合:
    # VIDEO_MIN_PIXELS = 128 * 28 * 28
    
    # ビデオフレームの最大トークン数。Qwen3-Omni-Flash の場合: 768 * 32 * 32
    VIDEO_MAX_PIXELS = 768 * 32 * 32
    # Qwen-Omni-Turbo の場合:
    # VIDEO_MAX_PIXELS = 768 * 28 * 28
    
    FPS = 2
    # 抽出されるフレームの最小数
    FPS_MIN_FRAMES = 4
    
    # 抽出されるフレームの最大数
    # Qwen3-Omni-Flash モデルで抽出されるフレームの最大数: 128
    # Qwen-Omni-Turbo モデルで抽出されるフレームの最大数: 80
    FPS_MAX_FRAMES = 128
    
    # ビデオ入力の最大画素値。Qwen3-Omni-Flash の場合: 16384 * 32 * 32
    VIDEO_TOTAL_PIXELS = 16384 * 32 * 32
    # Qwen-Omni-Turbo の場合:
    # VIDEO_TOTAL_PIXELS = 16384 * 28 * 28
    
    def round_by_factor(number, factor):
        return round(number / factor) * factor
    
    def ceil_by_factor(number, factor):
        return math.ceil(number / factor) * factor
    
    def floor_by_factor(number, factor):
        return math.floor(number / factor) * factor
    
    def get_video(video_path):
        cap = cv2.VideoCapture(video_path)
        frame_width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH))
        frame_height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT))
        total_frames = int(cap.get(cv2.CAP_PROP_FRAME_COUNT))
        video_fps = cap.get(cv2.CAP_PROP_FPS)
        cap.release()
        return frame_height, frame_width, total_frames, video_fps
    
    def smart_nframes(total_frames, video_fps):
        min_frames = ceil_by_factor(FPS_MIN_FRAMES, FRAME_FACTOR)
        max_frames = floor_by_factor(min(FPS_MAX_FRAMES, total_frames), FRAME_FACTOR)
        duration = total_frames / video_fps if video_fps != 0 else 0
        if duration - int(duration) > (1 / FPS):
            total_frames = math.ceil(duration * video_fps)
        else:
            total_frames = math.ceil(int(duration) * video_fps)
        nframes = total_frames / video_fps * FPS
        nframes = int(min(min(max(nframes, min_frames), max_frames), total_frames))
        if not (FRAME_FACTOR <= nframes <= total_frames):
            raise ValueError(f"nframes should in interval [{FRAME_FACTOR}, {total_frames}], but got {nframes}.")
        return nframes
    
    def smart_resize(height, width, nframes, factor=IMAGE_FACTOR):
        min_pixels = VIDEO_MIN_PIXELS
        total_pixels = VIDEO_TOTAL_PIXELS
        max_pixels = max(min(VIDEO_MAX_PIXELS, total_pixels / nframes * FRAME_FACTOR), int(min_pixels * 1.05))
        if max(height, width) / min(height, width) > MAX_RATIO:
            raise ValueError(f"absolute aspect ratio must be smaller than {MAX_RATIO}, got {max(height, width) / min(height, width)}")
        h_bar = max(factor, round_by_factor(height, factor))
        w_bar = max(factor, round_by_factor(width, factor))
        if h_bar * w_bar > max_pixels:
            beta = math.sqrt((height * width) / max_pixels)
            h_bar = floor_by_factor(height / beta, factor)
            w_bar = floor_by_factor(width / beta, factor)
        elif h_bar * w_bar < min_pixels:
            beta = math.sqrt(min_pixels / (height * width))
            h_bar = ceil_by_factor(height * beta, factor)
            w_bar = ceil_by_factor(width * beta, factor)
        return h_bar, w_bar
    
    def video_token_calculate(video_path):
        height, width, total_frames, video_fps = get_video(video_path)
        nframes = smart_nframes(total_frames, video_fps)
        resized_height, resized_width = smart_resize(height, width, nframes)
        video_token = int(math.ceil(nframes / FPS) * resized_height / 32 * resized_width / 32)
        video_token += 2  # ビジュアルマーク
        return video_token
    
    if __name__ == "__main__":
        video_path = "spring_mountain.mp4"  # ご自身のビデオパス
        video_token = video_token_calculate(video_path)
        print("video_tokens:", video_token)
  • audio_tokens

    • Qwen-Omni-Turbo: 合計トークン = オーディオの長さ (秒) × 25

    オーディオの長さが 1 秒未満の場合は、1 秒として計算されます。

無料クォータ

無料クォータの申請、照会、および利用方法の詳細については、「新規ユーザー向けの無料クォータ」をご参照ください。

レート制限

モデルのレート制限ルールとよくある質問については、「レート制限」をご参照ください。

エラーコード

呼び出しが失敗した場合、トラブルシューティングについては「エラーメッセージ」をご参照ください。

音声リスト

モデルはさまざまな音声をサポートしています。音声を使用するには、voice リクエストパラメーターを、以下の表の voice パラメーター列の対応する値に設定します。

Qwen3-Omni-Flash (非思考モード)

Qwen3-Omni-Flash モデルでは、非思考モードでのみ voice パラメーターを使用して音声を設定できます。思考モードでは、モデルはテキスト出力のみをサポートします。

名前

voice パラメーター

音声効果

説明

サポートされている言語

Cherry

Cherry

明るく、フレンドリで、自然な若い女性の声。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Ethan

Ethan

わずかに北方なまりのある標準中国語。明るく、温かく、エネルギッシュな声。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Nofish

Nofish

そり舌音を使わないデザイナー。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Jennifer

Jennifer

プレミアムで映画のようなアメリカ英語の女性の声。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Ryan

Ryan

リアリズムと緊張感のある、リズミカルでドラマチックな声。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Katerina

Katerina

成熟したリズミカルな女性の声。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Elias

Elias

学術的な厳密さと明確なストーリーテリングで複雑なトピックを説明します。

中国語、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Shanghai-Jada

Jada

上海出身の活発な女性。

中国語 (上海語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Beijing-Dylan

Dylan

北京の胡同で育ったティーンエイジャー。

中国語 (北京方言)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Sichuan-Sunny

Sunny

四川省出身の甘い女性の声。

中国語 (四川語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Nanjing-Li

Li

忍耐強いヨガの先生。

中国語 (南京方言)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Shaanxi-Marcus

Marcus

陝西省出身の誠実で深みのある声。

中国語 (陝西方言)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Man Nan-Roy

Roy

閩南語なまりのある、ユーモラスで活発な若い男性の声。

中国語 (閩南語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Tianjin-Peter

Peter

天津のクロストークのツッコミ役の声。

中国語 (天津方言)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Cantonese-Rocky

Rocky

オンラインチャット向けの、機知に富んだユーモラスな男性の声。

中国語 (広東語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Cantonese-Kiki

Kiki

香港出身の優しい親友。

中国語 (広東語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Sichuan-Eric

Eric

四川省成都出身の、型にはまらない洗練された男性の声。

中国語 (四川語)、英語、フランス語、ドイツ語、ロシア語、イタリア語、スペイン語、ポルトガル語、日本語、韓国語、タイ語

Qwen-Omni-Turbo

名前

voice パラメーター

音声効果

説明

サポートされている言語

Cherry

Cherry

明るく、フレンドリで、誠実な若い女性。

中国語、英語

Serena

Serena

親切な若い女性。

中国語、英語

Ethan

Ethan

わずかに北方なまりのある標準中国語。明るく、温かく、エネルギッシュな声。

中国語、英語

Chelsie

Chelsie

アニメ風のバーチャル彼女の声。

中国語、英語

オープンソース Qwen-Omni

名前

voice パラメーター

音声効果

説明

サポートされている言語

Ethan

Ethan

わずかに北方なまりのある標準中国語。明るく、温かく、エネルギッシュな声。

中国語、英語

Chelsie

Chelsie

アニメ風のバーチャル彼女の声。

中国語、英語