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

Alibaba Cloud Model Studio:Qwen-MT API リファレンス

最終更新日:Jun 26, 2026

OpenAI 互換インターフェイスまたは DashScope API を使用して Qwen-MT を呼び出す際の入力および出力パラメーター。

リファレンス: Machine Translation (Qwen-MT)

OpenAI 互換

中国 (北京) リージョン

SDK 用の base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

シンガポール リージョン

SDK 用の base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

米国 (バージニア) リージョン

SDK 用の base_url: https://dashscope-us.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions

シンガポール リージョン

SDK 用の base_url: https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions

米国 (バージニア) リージョン

SDK 用の base_url: https://dashscope-us.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions

中国 (北京) リージョン

SDK 用の base_url: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions

重要

Model Studio は、中国 (北京)、シンガポール、および中国 (香港) リージョン向けにワークスペース専用ドメインをリリースしました。新しい専用ドメインは、推論リクエストに対して優れたパフォーマンスと高い安定性を提供します。新しいドメインへの移行を推奨します。

  • 中国 (北京): https://dashscope.aliyuncs.com から https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com

  • シンガポール: https://dashscope-intl.aliyuncs.com から https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com

  • 中国 (香港): https://cn-hongkong.dashscope.aliyuncs.com から https://{WorkspaceId}.cn-hongkong.maas.aliyuncs.com

{WorkspaceId} はご利用のワークスペース ID です。この ID は Model Studio コンソールの ワークスペース詳細 ページで確認できます。既存のドメインは引き続き完全に機能します。

まず、API キーを作成し、環境変数として設定してください。OpenAI SDK を使用する場合は、SDK をインストールしてください。

リクエスト本文

基本的な使用方法

Python

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "No me reí después de ver este video"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English"
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// Node.js v18 以降が必要です。コードは ES Module 環境で実行してください。
    import OpenAI from "openai";

    const openai = new OpenAI(
        {
            // 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
            apiKey: process.env.DASHSCOPE_API_KEY,
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
        }
    );
    const completion = await openai.chat.completions.create({
        model: "qwen-mt-plus", 
        messages: [
            { role: "user", content: "No me reí después de ver este video" }
        ],
        translation_options: {
            source_lang: "auto",
            target_lang: "English"
        }
    });
    console.log(JSON.stringify(completion));

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
        "model": "qwen-mt-plus",
        "messages": [{"role": "user", "content": "No me reí después de ver este video"}],
        "translation_options": {
          "source_lang": "auto",
          "target_lang": "English"
          }
    }'
    

用語介入

Python

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "terms": [
        {
            "source": "biosensor",
            "target": "biological sensor"
        },
        {
            "source": "grafeno",
            "target": "graphene"
        },
        {
            "source": "elementos químicos",
            "target": "chemical elements"
        },
        {
            "source": "estado de salud del cuerpo",
            "target": "health status of the body"
        }
    ]
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えてください。
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// Node.js v18 以降が必要です。コードは ES Module 環境で実行してください。
    import OpenAI from "openai";

    const openai = new OpenAI(
        {
            // 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
            apiKey: process.env.DASHSCOPE_API_KEY,
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
        }
    );
    const completion = await openai.chat.completions.create({
        model: "qwen-mt-plus",
        messages: [
            { role: "user", content: "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa." }
        ],
        translation_options: {
            source_lang: "auto",
            target_lang: "English",
            terms: [
                {
                    "source": "biosensor",
                    "target": "biological sensor"
                },
                {
                    "source": "grafeno",
                    "target": "graphene"
                },
                {
                    "source": "elementos químicos",
                    "target": "chemical elements"
                },
                {
                    "source": "estado de salud del cuerpo",
                    "target": "health status of the body"
                }
            ]
        }
    });
    console.log(JSON.stringify(completion));

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

# 次の URL はシンガポールリージョン用です。呼び出し時に、WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "qwen-mt-plus",
      "messages": [
        {
          "role": "user",
          "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
        }
      ],
      "translation_options": {
        "source_lang": "auto",
        "target_lang": "English",
        "terms": [
          {
            "source": "biosensor",
            "target": "biological sensor"
          },
          {
            "source": "grafeno",
            "target": "graphene"
          },
          {
            "source": "elementos químicos",
            "target": "chemical elements"
          },
          {
            "source": "estado de salud del cuerpo",
            "target": "health status of the body"
          }
        ]
      }
    }'

翻訳メモリ

Python

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "El siguiente comando muestra la información de la versión de Thrift instalada."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
            "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
        },
        {
            "source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
            "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
        }
    ]
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えてください。
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// Node.js v18 以降が必要です。コードは ES Module 環境で実行してください。
    import OpenAI from "openai";

    const openai = new OpenAI(
        {
            // 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
            apiKey: process.env.DASHSCOPE_API_KEY,
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
        }
    );
    const completion = await openai.chat.completions.create({
        model: "qwen-mt-plus",
        messages: [
            { role: "user", content: "El siguiente comando muestra la información de la versión de Thrift instalada." }
        ],
        translation_options: {
            source_lang: "auto",
            target_lang: "English",
            tm_list: [
                {
                    "source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
                    "target": "You can use one of the following methods to query the engine version of a cluster:"
                },
                {
                    "source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
                    "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
                },
                {
                    "source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
                    "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
                }
            ]
        }
    });
    console.log(JSON.stringify(completion));

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "qwen-mt-plus",
      "messages": [
        {
          "role": "user",
          "content": "El siguiente comando muestra la información de la versión de Thrift instalada."
        }
      ],
      "translation_options": {
        "source_lang": "auto",
        "target_lang": "English",
        "tm_list":[
              {"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
              {"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
              {"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
        ]
      }
    }'
    

ドメインプロンプト

Python

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合は、ご自身の Model Studio API キーに置き換えます: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 次の URL はシンガポールリージョン用です。呼び出し時に、WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "domains": "この文章は Ali Cloud の IT ドメインのものです。主に、コンピューターのソフトウェアおよびハードウェアに関連する多数の用語を含む、コンピューター関連のソフトウェア開発と使用方法を扱います。翻訳の際は、トラブルシューティングに関する専門用語や構文のパターンにご注意ください。この IT ドメインのスタイルで翻訳してください。"
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// Node.js v18 以降が必要です。コードは ES Module 環境で実行してください。
    import OpenAI from "openai";

    const openai = new OpenAI(
        {
            // 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: apiKey: "sk-xxx"
            apiKey: process.env.DASHSCOPE_API_KEY,
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1"
        }
    );
    const completion = await openai.chat.completions.create({

        model: "qwen-mt-plus",
        messages: [
            { role: "user", content: "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT." }
        ],
        translation_options: {
            source_lang: "auto",
            target_lang: "English",
            domains: "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
        }
    });
    console.log(JSON.stringify(completion));

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
    -H "Authorization: Bearer $DASHSCOPE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "qwen-mt-plus",
      "messages": [
        {
          "role": "user",
          "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
        }
      ],
      "translation_options": {
        "source_lang": "auto",
        "target_lang": "English",
        "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
      }
    }'
    

model string (必須)

モデル名。サポートされているモデル: qwen-mt-plus、qwen-mt-flash、qwen-mt-lite、qwen-mt-turbo。

messages array (必須)

モデルにコンテキストを提供するメッセージの配列。ユーザーからのメッセージのみサポートされます。

メッセージタイプ

ユーザー メッセージ object (必須)

翻訳対象の文を含むユーザー メッセージ。

プロパティ

content string (必須)

翻訳対象の文。

role string (必須)

ユーザー メッセージのロール。必ず user に設定してください。

stream boolean (オプション) デフォルト値は false です。

ストリーミング出力モードを有効にします。

有効値:

  • false: 生成後に完全な応答を返します。

  • true: 生成された内容をチャンク単位で返します。クライアント側でチャンクを再構築して完全な応答を生成します。

説明

qwen-mt-flash および qwen-mt-lite は増分出力 (各チャンクには新しいコンテンツのみ含まれる) を返します。qwen-mt-plus および qwen-mt-turbo は非増分出力 (各チャンクにはそれまでの全シーケンスが含まれる) を返します。この動作は変更できません。例:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

stream_options object (オプション)

ストリーミング出力の設定項目。このパラメーターは streamtrue に設定されている場合にのみ有効になります。

プロパティ

include_usage boolean (オプション) デフォルト値は false です。

最後のデータチャンク にトークン消費情報が含まれます。

有効値:

  • true

  • false

max_tokens integer (オプション)

生成されるトークンの最大数。出力がこの値を超える場合、応答は切り捨てられます。

デフォルト値および最大値は、モデルの最大出力長です。詳細については、「モデル選択」をご参照ください。

seed integer (オプション)

再現可能な結果を得るための乱数シード。同じ seed およびパラメーターを使用すると、一貫した出力が得られます。

値の範囲: [0, 2<sup>31</sup>-1]

temperature float (オプション) デフォルト値は 0.65 です。

生成テキストの多様性を制御するサンプリング温度。

値が高いほど多様なテキストが生成され、値が低いほど決定論的なテキストが生成されます。

値の範囲: [0, 2)

temperature および top_p の両方がテキストの多様性を制御します。いずれか一方のみを設定してください。

top_p float (オプション) デフォルト値は 0.8 です。

生成テキストの多様性を制御する核サンプリングの確率しきい値。

値が高いほど多様なテキストが生成され、値が低いほど決定論的なテキストが生成されます。

値の範囲: (0, 1.0]

temperature および top_p の両方がテキストの多様性を制御します。いずれか一方のみを設定してください。

top_k integer (オプション) デフォルト値は 1 です。

生成時のサンプリングにおけるサンプル候補セットのサイズ。たとえば、これを 50 に設定すると、スコア上位 50 トークンのみがサンプリングプールとなります。値が大きいほどランダム性が高まり、値が小さいほど決定論的になります。値が None または 100 を超える場合、top_k は無効化され、top_p のみが有効になります。

値は 0 以上である必要があります。

OpenAI 標準外のパラメーターです。Python SDK の場合は extra_body オブジェクト内に記述してください extra_body={"top_k": xxx}。Node.js SDK または HTTP 呼び出しの場合は、トップレベルのパラメーターとして渡してください。

repetition_penalty float (オプション) デフォルト値は 1.0 です。

連続するシーケンス内の繰り返しに対するペナルティ。値が高いほど繰り返しが減少します。1.0 の場合はペナルティが適用されません。値は 0 より大きくなければならず、上限はありません。

OpenAI 標準外のパラメーターです。Python SDK の場合は extra_body オブジェクト内に記述してください extra_body={"repetition_penalty": xxx}。Node.js SDK または HTTP 呼び出しの場合は、トップレベルのパラメーターとして渡してください。

translation_options object (必須)

翻訳パラメーター。

プロパティ

source_lang string (必須)

ソース言語の英語フルネーム。詳細については、「サポート言語」をご参照ください。auto に設定すると、モデルが入力言語を自動検出します。

target_lang string (必須)

ターゲット言語の英語フルネーム。詳細については、「サポート言語」をご参照ください。

terms arrays (オプション)

用語介入 機能を使用する際に設定する用語の配列。

プロパティ

source string (必須)

ソース言語の用語。

target string (必須)

ターゲット言語の用語。

tm_list arrays (オプション)

翻訳メモリ 機能を使用する際に設定する翻訳メモリの配列。

プロパティ

source string (必須)

ソース言語の文。

target string (必須)

ターゲット言語の文。

domains string (オプション)

ドメインプロンプト 機能を使用する際に設定するドメインプロンプト。

ドメインプロンプトは英語で記述する必要があります。

OpenAI 標準外のパラメーターです。Python SDK の場合は extra_body オブジェクト内に記述してください extra_body={"translation_options": xxx}。Node.js SDK または HTTP 呼び出しの場合は、トップレベルのパラメーターとして渡してください。

チャット応答オブジェクト (非ストリーミング出力)

{
  "id": "chatcmpl-999a5d8a-f646-4039-968a-167743ae0f22",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "I didn't laugh after watching this video.",
        "refusal": null,
        "role": "assistant",
        "annotations": null,
        "audio": null,
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1762346157,
  "model": "qwen-mt-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 9,
    "prompt_tokens": 53,
    "total_tokens": 62,
    "completion_tokens_details": null,
    "prompt_tokens_details": null
  }
}

id string

一意のリクエスト ID。

choices array

モデルが生成したコンテンツの配列。

プロパティ

finish_reason string

モデルがコンテンツの生成を停止した理由。

有効値:

  • stop: 出力が完了しました。

  • length: 出力長の制限に達しました。

index integer

choices 配列内の現在のオブジェクトのインデックス。

message object

モデルの出力メッセージ。

プロパティ

content string

翻訳結果。

refusal string

現在は固定で null です。

role string

メッセージのロール。固定で assistant です。

audio object

現在は固定で null です。

function_call object

現在は固定で null です。

tool_calls array

現在は固定で null です。

created integer

リクエストが作成された UNIX タイムスタンプ。

model string

リクエストに使用されたモデル。

object string

常に chat.completion です。

service_tier string

現在は固定で null です。

system_fingerprint string

現在は固定で null です。

usage object

リクエストのトークン消費量。

プロパティ

completion_tokens integer

モデル出力のトークン数。

prompt_tokens integer

入力のトークン数。

total_tokens integer

消費されたトークンの合計数。prompt_tokens + completion_tokens に等しいです。

completion_tokens_details object

現在は固定で null です。

prompt_tokens_details object

現在は固定で null です。

チャット応答チャンクオブジェクト (ストリーミング出力)

増分出力

{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": "assistant", "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "I", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " didn", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "'t", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " laugh", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " after", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " watching", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " this", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " video", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": ".", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": "stop", "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": "stop", "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": {"completion_tokens": 9, "prompt_tokens": 56, "total_tokens": 65, "completion_tokens_details": null, "prompt_tokens_details": null}}

非増分出力

{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":9,"prompt_tokens":56,"total_tokens":65,"completion_tokens_details":null,"prompt_tokens_details":null}}

id string

呼び出しの一意の ID。各チャンクオブジェクトは同じ ID を持ちます。

choices array

モデルが生成したコンテンツの配列。include_usagetrue に設定されている場合、最後のチャンクではこの配列は空になります。

プロパティ

delta object

ストリーミングモードで返される出力コンテンツ。

プロパティ

content string

翻訳結果。qwen-mt-flash および qwen-mt-lite は増分更新を提供します。qwen-mt-plus および qwen-mt-turbo は非増分更新を提供します。

function_call object

現在は固定で null です。

refusal object

現在は固定で null です。

role string

メッセージオブジェクトのロール。最初のチャンクでのみ値を持ちます。

finish_reason string

モデルがコンテンツの生成を停止する理由は以下の 3 つのいずれかです。

  • 出力が完了した場合、値は stop です。

  • 生成中の場合、値は null です。

  • length: 出力長の制限に達したため生成が停止しました。

index integer

choices 配列内の現在の応答のインデックス。

created integer

リクエストが作成された UNIX タイムスタンプ。各チャンクは同じタイムスタンプを持ちます。

model string

リクエストに使用されたモデル。

object string

常に chat.completion.chunk です。

service_tier string

現在は固定で null です。

system_fingerprint string

現在は固定で null です。

usage object

リクエストのトークン消費量。include_usagetrue の場合にのみ、最後のチャンクで返されます。

プロパティ

completion_tokens integer

モデル出力のトークン数。

prompt_tokens integer

入力トークン数。

total_tokens integer

トークンの合計数。prompt_tokenscompletion_tokens の合計です。

completion_tokens_details object

現在は固定で null です。

prompt_tokens_details object

現在は固定で null です。

DashScope

北京

HTTP エンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しの場合、base_url を設定する必要はありません。デフォルト値は https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1 です。

シンガポール

HTTP エンドポイント: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

base_url を次のように設定します。

Python コード

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

Java コード

  • 方法 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
  • 方法 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

バージニア

HTTP エンドポイント: POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation

base_url を次のように設定します。

Python コード

dashscope.base_http_api_url = 'https://dashscope-us.aliyuncs.com/api/v1'

Java コード

  • 方法 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-us.aliyuncs.com/api/v1");
  • 方法 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://dashscope-us.aliyuncs.com/api/v1";

シンガポール

HTTP エンドポイント: POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

base_url を次のように設定します。

Python コード

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

Java コード

  • 方法 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
  • 方法 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";

バージニア

HTTP エンドポイント: POST https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation

base_url を次のように設定します。

Python コード

dashscope.base_http_api_url = 'https://dashscope-us.aliyuncs.com/api/v1'

Java コード

  • 方法 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-us.aliyuncs.com/api/v1");
  • 方法 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://dashscope-us.aliyuncs.com/api/v1";

北京

HTTP エンドポイント: POST https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しの場合、base_url を設定する必要はありません。デフォルト値は https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1 です。

API キーを作成し、環境変数としてエクスポートする必要があります。DashScope SDK を使用する場合は、DashScope SDK をインストールしてください。

リクエスト本文

基本的な使用方法

Python

import os
import dashscope

# 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "No me reí después de ver este video"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
}
response = dashscope.Generation.call(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えてください。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 2.20.6 以降が必要です。
    import java.lang.System;
    import java.util.Collections;
    import com.alibaba.dashscope.aigc.generation.Generation;
    import com.alibaba.dashscope.aigc.generation.GenerationParam;
    import com.alibaba.dashscope.aigc.generation.GenerationResult;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions;
    import com.alibaba.dashscope.common.Message;
    import com.alibaba.dashscope.common.Role;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.Constants;

    public class Main {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content("No me reí después de ver este video")
                    .build();
            TranslationOptions options = TranslationOptions.builder()
                    .sourceLang("auto")
                    .targetLang("English")
                    .build();
            GenerationParam param = GenerationParam.builder()
                    // 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えてください: .apiKey("sk-xxx")
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("qwen-mt-plus")
                    .messages(Collections.singletonList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .translationOptions(options)
                    .build();
            return gen.call(param);
        }
        public static void main(String[] args) {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
            try {
                GenerationResult result = callWithMessage();
                System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.err.println("Error message: "+e.getMessage());
                e.printStackTrace();
            } finally {
                System.exit(0);
            }
        }
    }

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
    -H "Authorization: $DASHSCOPE_API_KEY" \
    -H "Content-Type: application/json" \
    -d '{
      "model": "qwen-mt-plus",
      "input": {
        "messages": [
          {
            "content": "No me reí después de ver este video",
            "role": "user"
          }
        ]
      },
      "parameters": {
        "translation_options": {
          "source_lang": "auto",
          "target_lang": "English"
        }
      }
    }'

用語介入

Python

import os
import dashscope

# 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "terms": [
        {
            "source": "biosensor",
            "target": "biological sensor"
        },
        {
            "source": "grafeno",
            "target": "graphene"
        },
        {
            "source": "elementos químicos",
            "target": "chemical elements"
        },
        {
            "source": "estado de salud del cuerpo",
            "target": "health status of the body"
        }
    ]
}
response = dashscope.Generation.call(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えてください。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 2.20.6 以降が必要です。
    import java.lang.System;
    import java.util.Collections;
    import java.util.Arrays;
    import com.alibaba.dashscope.aigc.generation.Generation;
    import com.alibaba.dashscope.aigc.generation.GenerationParam;
    import com.alibaba.dashscope.aigc.generation.GenerationResult;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions.Term;
    import com.alibaba.dashscope.common.Message;
    import com.alibaba.dashscope.common.Role;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.Constants;

    public class Main {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content("Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.")
                    .build();
            Term term1 = Term.builder()
                    .source("biosensor")
                    .target("biological sensor")
                    .build();
            Term term2 = Term.builder()
                    .source("estado de salud del cuerpo")
                    .target("health status of the body")
                    .build();
            TranslationOptions options = TranslationOptions.builder()
                    .sourceLang("auto")
                    .targetLang("English")
                    .terms(Arrays.asList(term1, term2))
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("qwen-mt-plus")
                    .messages(Collections.singletonList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .translationOptions(options)
                    .build();
            return gen.call(param);
        }
        public static void main(String[] args) {
            try {
                GenerationResult result = callWithMessage();
                System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.err.println("Error message: "+e.getMessage());
            }
            System.exit(0);
        }
    }

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
    -H "Authorization: $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "qwen-mt-plus",
      "input": {
        "messages": [
          {
            "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.",
            "role": "user"
          }
        ]
      },
      "parameters": {
        "translation_options": {
          "source_lang": "auto",
          "target_lang": "English",
          "terms": [
            {
              "source": "biosensor",
              "target": "biological sensor"
            },
            {
              "source": "estado de salud del cuerpo",
              "target": "health status of the body"
            }
          ]
        }
      }
    }'

翻訳メモリ

Python

import os
import dashscope

# 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "El siguiente comando muestra la información de la versión de Thrift instalada."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
            "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
        },
        {
            "source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
            "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
        }
    ]}
response = dashscope.Generation.call(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えてください。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 2.20.6 以降が必要です。
    import java.lang.System;
    import java.util.Collections;
    import java.util.Arrays;
    import com.alibaba.dashscope.aigc.generation.Generation;
    import com.alibaba.dashscope.aigc.generation.GenerationParam;
    import com.alibaba.dashscope.aigc.generation.GenerationResult;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions.Tm;
    import com.alibaba.dashscope.common.Message;
    import com.alibaba.dashscope.common.Role;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.Constants;

    public class Main {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content("El siguiente comando muestra la información de la versión de Thrift instalada.")
                    .build();
            Tm tm1 = Tm.builder()
                    .source("Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:")
                    .target("You can use one of the following methods to query the engine version of a cluster:")
                    .build();
            Tm tm2 = Tm.builder()
                    .source("La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.")
                    .target("The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website.")
                    .build();
            Tm tm3 = Tm.builder()
                    .source("Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:")
                    .target("You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:")
                    .build();
            TranslationOptions options = TranslationOptions.builder()
                    .sourceLang("auto")
                    .targetLang("English")
                    .tmList(Arrays.asList(tm1, tm2, tm3))
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                    .model("qwen-mt-plus")
                    .messages(Collections.singletonList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .translationOptions(options)
                    .build();
            return gen.call(param);
        }
        public static void main(String[] args) {
            try {
                GenerationResult result = callWithMessage();
                System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.err.println("Error message: "+e.getMessage());
            }
            System.exit(0);
        }
    }

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
    -H "Authorization: $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "qwen-mt-plus",
      "input": {
        "messages": [
          {
            "content": "El siguiente comando muestra la información de la versión de Thrift instalada.",
            "role": "user"
          }
        ]
      },
      "parameters": {
        "translation_options": {
          "source_lang": "auto",
          "target_lang": "English",
          "tm_list":[
              {"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
              {"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
              {"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
          ]
        }
      }
    }'

ドメインプロンプト

Python

import os
import dashscope

# 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
    "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
response = dashscope.Generation.call(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えてください: api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 2.20.6 以降が必要です。
    import java.lang.System;
    import java.util.Collections;
    import com.alibaba.dashscope.aigc.generation.Generation;
    import com.alibaba.dashscope.aigc.generation.GenerationParam;
    import com.alibaba.dashscope.aigc.generation.GenerationResult;
    import com.alibaba.dashscope.aigc.generation.TranslationOptions;
    import com.alibaba.dashscope.common.Message;
    import com.alibaba.dashscope.common.Role;
    import com.alibaba.dashscope.exception.ApiException;
    import com.alibaba.dashscope.exception.InputRequiredException;
    import com.alibaba.dashscope.exception.NoApiKeyException;
    import com.alibaba.dashscope.protocol.Protocol;
import com.alibaba.dashscope.utils.Constants;

    public class Main {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
        public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
            // 以下はシンガポールリージョンの URL です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。URL はリージョンによって異なります。
            Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            Message userMsg = Message.builder()
                    .role(Role.USER.getValue())
                    .content("La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.")
                    .build();
            TranslationOptions options = TranslationOptions.builder()
                    .sourceLang("auto")
                    .targetLang("English")
                    .domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
                    .build();
            GenerationParam param = GenerationParam.builder()
                    .apiKey(System.getenv("DASHSCOPE_API_KEY"))

                    .model("qwen-mt-plus")
                    .messages(Collections.singletonList(userMsg))
                    .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                    .translationOptions(options)
                    .build();
            return gen.call(param);
        }
        public static void main(String[] args) {
        // 以下は中国北部 2(北京)地域の設定です。呼び出し時に WorkspaceId を実際のワークスペース ID に置き換えてください。各地域の設定は異なります。
        Constants.baseHttpApiUrl = "https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1";
            try {
                GenerationResult result = callWithMessage();
                System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
            } catch (ApiException | NoApiKeyException | InputRequiredException e) {
                System.err.println("Error message: "+e.getMessage());
            }
            System.exit(0);
        }
    }

curl

エンドポイントおよび API キーはリージョンによって異なります。以下はシンガポール エンドポイントです。

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
    -H "Authorization: $DASHSCOPE_API_KEY" \
    -H 'Content-Type: application/json' \
    -d '{
      "model": "qwen-mt-plus",
      "input": {
        "messages": [
          {
            "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.",
            "role": "user"
          }
        ]
      },
      "parameters": {
        "translation_options": {
          "source_lang": "auto",
          "target_lang": "English",
          "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
      }
    }'

model string (必須)

モデル名。サポートされているモデル: qwen-mt-plus、qwen-mt-flash、qwen-mt-lite、qwen-mt-turbo。

messages array (必須)

モデルにコンテキストを提供するメッセージの配列。ユーザーからのメッセージのみサポートされます。

メッセージタイプ

ユーザー メッセージ object (必須)

翻訳対象の文を含むユーザー メッセージ。

プロパティ

content string (必須)

翻訳対象の文。

role string (必須)

ユーザー メッセージのロール。必ず user に設定してください。

max_tokens integer (オプション)

生成されるトークンの最大数。出力がこの値を超える場合、応答は切り捨てられます。

デフォルト値および最大値は、モデルの最大出力長です。詳細については、「モデル選択」をご参照ください。

Java SDK では、パラメーターは maxTokens です。 HTTP 呼び出しの場合は、parameters オブジェクト内に max_tokens を配置してください。

seed integer (オプション)

再現可能な結果を得るための乱数シード。同じ seed およびパラメーターを使用すると、一貫した出力が得られます。

値の範囲: [0, 2<sup>31</sup>-1]

HTTP 呼び出しを行う場合、seedparameters オブジェクト内に配置してください。

temperature float (オプション) デフォルト値は 0.65 です。

生成テキストの多様性を制御するサンプリング温度。

値が高いほど多様なテキストが生成され、値が低いほど決定論的なテキストが生成されます。

値の範囲: [0, 2)

temperature および top_p の両方がテキストの多様性を制御します。いずれか一方のみを設定してください。

HTTP 呼び出しを行う場合、temperatureparameters オブジェクト内に配置してください。

top_p float (オプション) デフォルト値は 0.8 です。

生成テキストの多様性を制御する核サンプリングの確率しきい値。

値が高いほど多様なテキストが生成され、値が低いほど決定論的なテキストが生成されます。

値の範囲: (0, 1.0]

temperature および top_p の両方がテキストの多様性を制御します。いずれか一方のみを設定してください。

Java SDK では、パラメーターは topPparameters オブジェクトです。

repetition_penalty float (オプション) デフォルト値は 1.0 です。

連続するシーケンス内の繰り返しに対するペナルティ。値が高いほど繰り返しが減少します。1.0 の場合はペナルティが適用されません。値は 0 より大きくなければならず、上限はありません。

Java SDK では、パラメーターは repetitionPenalty です。 HTTP 呼び出しの場合は、parameters オブジェクトに repetition_penalty を追加してください。

top_k integer (オプション) デフォルト値は 1 です。

生成時のサンプリングにおけるサンプル候補セットのサイズ。たとえば、これを 50 に設定すると、スコア上位 50 トークンのみがサンプリングプールとなります。値が大きいほどランダム性が高まり、値が小さいほど決定論的になります。値が None または 100 を超える場合、top_k は無効化され、top_p のみが有効になります。

値は 0 以上である必要があります。

Java SDK では、パラメーターは topK です。 HTTP 呼び出しを行う場合、parameters オブジェクト内に top_k を設定してください。

stream boolean (オプション)

ストリーミング出力モードを有効にします。

有効値:

  • false: 生成後に完全な応答を返します。

  • true: 生成された内容をチャンク単位で返します。クライアント側でチャンクを再構築して完全な応答を生成します。

説明

qwen-mt-flash および qwen-mt-lite は増分出力 (各チャンクには新しいコンテンツのみ含まれる) を返します。qwen-mt-plus および qwen-mt-turbo は非増分出力 (各チャンクにはそれまでの全シーケンスが含まれる) を返します。この動作は変更できません。例:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

このパラメーターは Python SDK のみでサポートされています。Java SDK でストリーミング出力を実装するには、streamCall インターフェイスを呼び出してください。HTTP 呼び出しでストリーミング出力を実装するには、ヘッダーに X-DashScope-SSEenable に設定してください。

translation_options object (必須)

翻訳パラメーター。

プロパティ

source_lang string (必須)

ソース言語の英語フルネーム。詳細については、「サポート言語」をご参照ください。auto に設定すると、モデルが入力言語を自動検出します。

target_lang string (必須)

ターゲット言語の英語フルネーム。詳細については、「サポート言語」をご参照ください。

terms arrays (オプション)

用語介入 機能を使用する際に設定する用語の配列。

プロパティ

source string (必須)

ソース言語の用語。

target string (必須)

ターゲット言語の用語。

tm_list arrays (オプション)

翻訳メモリ 機能を使用する際に設定する翻訳メモリの配列。

プロパティ

source string (必須)

ソース言語の文。

target string (必須)

ターゲット言語の文。

domains string (オプション)

ドメインプロンプト 機能を使用する際に設定するドメインプロンプト。

ドメインプロンプトは英語で記述する必要があります。
Java SDK では、パラメーターは translationOptions です。HTTP 呼び出しを行う場合、translation_optionsparameters オブジェクト内に配置してください。

チャット応答オブジェクト (ストリーミングおよび非ストリーミング出力で共通)

{
  "status_code": 200,
  "request_id": "9b4ec3b2-6d29-40a6-a08b-7e3c9a51c289",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": "stop",
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "I didn't laugh after watching this video."
        }
      }
    ],
    "model_name": "qwen-mt-plus"
  },
  "usage": {
    "input_tokens": 53,
    "output_tokens": 9,
    "total_tokens": 62
  }
}

status_code string

リクエストの状態コード。200 は成功を示し、その他の値は失敗を示します。

Java SDK はこのパラメーターを返しません。呼び出しが失敗した場合、例外がスローされます。例外メッセージには status_code および message の内容が含まれます。

request_id string

一意のリクエスト ID。

Java SDK では、返されるパラメーターは requestId.

code string

エラーコード。成功時は空です。

Python SDK のみがこのパラメーターを返します。

output object

呼び出し結果。

プロパティ

text string

現在は固定で null です。

finish_reason string

モデルがコンテンツの生成を停止した理由。有効値:

  • 生成中の場合、値は null です。

  • stop: モデルが自然にコンテンツの生成を停止しました。

  • length: 出力長の制限に達したため生成が停止しました。

choices array

モデルの出力。

プロパティ

finish_reason string

有効値:

  • 生成中の場合、値は null です。

  • stop: モデルが自然にコンテンツの生成を停止しました。

  • length: 出力長の制限に達したため生成が停止しました。

message object

モデルの出力メッセージ。

プロパティ

role string

出力メッセージのロール。固定で assistant です。

content string

翻訳結果。

model_name string

このリクエストに使用されたモデル。

usage object

リクエストのトークン使用量。

プロパティ

input_tokens integer

入力トークン数。

output_tokens integer

出力トークン数。

total_tokens integer

トークンの合計数。input_tokens + output_tokens に等しいです。

エラーコード

呼び出しが失敗した場合は、「エラーコード」を参照して問題を解決してください。