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

:Qwen-MT API リファレンス

最終更新日:Oct 27, 2026

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

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

OpenAI 互換

シンガポールリージョン

base_url (SDK 用): 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://{WorkspaceId}.us-east-1.maas.aliyuncs.com/compatible-mode/v1

HTTP エンドポイント: POST https://{WorkspaceId}.us-east-1.maas.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

重要Alibaba Cloud 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 であり、Alibaba Cloud 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 モジュール環境で実行してください。
    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 モジュール環境で実行してください。
    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 モジュール環境で実行してください。
    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 モジュール環境で実行してください。
    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。

messages array (必須)

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

メッセージタイプ

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

翻訳する文を含むユーザーメッセージ。

プロパティ

content string (必須)

翻訳する文。

role string (必須)

ユーザーメッセージのロールです。値は user に設定する必要があります。

ストリーム boolean (任意) デフォルト値は false です。

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

有効値:

  • false:生成後に完全な応答を返します。
  • true:生成されたチャンクで応答を返します。クライアントはチャンクから完全な応答を再構築します。

注記qwen-mt-flash と qwen-mt-lite は増分的にデータを返します (各チャンクには新しいコンテンツのみが含まれます)。qwen-mt-plus は非増分的にデータを返します (各チャンクには現在までのシーケンス全体が含まれます)。この動作は変更できません。例:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

stream_options object (任意)

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

プロパティ

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_usageがtrueに設定されている場合、この配列は最後のチャンクでは空になります。

プロパティ

delta object

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

プロパティ

content string

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

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_usage が true の場合にのみ、最後のチャンクで返されます。

プロパティ

completion_tokens integer

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

prompt_tokens integer

入力トークンの数。

total_tokens integer

トークンの総数。prompt_tokens と completion_tokens の合計です。

completion_tokens_details object

現在、null に固定されています。

prompt_tokens_details object

現在、null に固定されています。

DashScope

シンガポール

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

SDK 呼び出しのリージョン設定:

Python コード

import os
import dashscope

# 以下はシンガポールリージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

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://{WorkspaceId}.us-east-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しのリージョン設定:

Python コード

import os
import dashscope

# 以下は米国 (バージニア) リージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    workspace="{WorkspaceId}",
    region="us-east-1",
)

Java コード

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

北京

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

SDK 呼び出しではアクセスアドレスを設定する必要はありません。Client を構築する際に、workspace と region パラメーターでリージョンを指定します(デフォルトは中国 (北京) リージョンです)。

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

リクエストボディ

基本的な使用法

Python

import os
import dashscope

# 以下はシンガポールリージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

messages = [
    {
        "role": "user",
        "content": "No me reí después de ver este video"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
}
response = client.chat.completions.create(
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えることができます。
    messages=messages,
    parameters={"translation_options": translation_options}
)
print(response.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 {
        // 以下は中国 (北京) リージョンの base_url です。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) {
        // 以下は中国 (北京) リージョンの base_url です。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

# 以下はシンガポールリージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

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 = client.chat.completions.create(
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えることができます。
    messages=messages,
    parameters={"translation_options": translation_options}
)
print(response.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 {
        // 以下は中国 (北京) リージョンの base_url です。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

# 以下はシンガポールリージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

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 = client.chat.completions.create(
    model="qwen-mt-plus",  # この例では qwen-mt-plus を使用しています。必要に応じてモデル名を置き換えることができます。
    messages=messages,
    parameters={"translation_options": translation_options}
)
print(response.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 {
        // 以下は中国 (北京) リージョンの base_url です。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

# 以下はシンガポールリージョンの設定です。リージョンによって region の値は異なります。呼び出し時は、{WorkspaceId} をお使いのワークスペース ID に置き換えてください。
client = dashscope.Client(
    # 環境変数が設定されていない場合は、Model Studio API キーに置き換えます: api_key="sk-xxx"
    # API キーはリージョン固有です。API キーを取得するには、https://www.alibabacloud.com/help/model-studio/get-api-key をご参照ください
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    workspace="{WorkspaceId}",
    region="ap-southeast-1",
)

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 = client.chat.completions.create(
    model="qwen-mt-plus",
    messages=messages,
    parameters={"translation_options": translation_options}
)
print(response.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 {
        // 以下は中国 (北京) リージョンの base_url です。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) {
        // 以下は中国 (北京) リージョンの base_url です。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。

messages array (必須)

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

メッセージタイプ

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

翻訳する文を含むユーザーメッセージ。

プロパティ

content string (必須)

翻訳する文。

role string (必須)

ユーザーメッセージのロール。user に設定する必要があります。

max_tokens integer (任意)

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

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

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

seed integer (任意)

再現性のある結果を得るための乱数シードです。同じ seed とパラメーターを使用すると、一貫した出力が生成されます。

有効値: [0, 2<sup>31</sup>-1]。

HTTP 呼び出しを行う場合、seed を parameters オブジェクトに配置します。

temperature float (任意) デフォルトは 0.65 です。

生成されるテキストの多様性をコントロールするサンプリング温度。

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

有効値: [0, 2)

temperature と top_p はどちらもテキストの多様性をコントロールします。どちらか一方のみを設定してください。

HTTP 呼び出しを行う場合、temperature を parameters オブジェクトに配置します。

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 呼び出しの場合、repetition_penalty を parameters オブジェクトに追加します。

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 は非増分的にデータを返します (各チャンクには現在までのシーケンス全体が含まれます)。この動作は変更できません。例:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

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

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 呼び出しを行う際、parameters オブジェクトに translation_options を配置します。

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

Python SDK の呼び出しが失敗すると DashScopeError がスローされます。e.code/e.status_code/e.message/e.request_id でエラー情報を取得できます。Java SDK の呼び出しが失敗すると ApiException がスローされ、ApiException.getStatus().getStatusCode() でエラーステータスコードを取得できます。

{
  "request_id": "9b4ec3b2-6d29-40a6-a08b-7e3c9a51c289",
  "choices": [
    {
      "index": 0,
      "finish_reason": "stop",
      "message": {
        "role": "assistant",
        "content": "I didn't laugh after watching this video."
      }
    }
  ],
  "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 と等しくなります。

エラーコード

モデル呼び出しが失敗した場合、Python SDK は DashScopeError をスローします。e.code/e.message/e.request_id でエラー情報を取得できます。問題解決については「エラーコード」をご参照ください。