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

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

最終更新日:Jan 31, 2026

このトピックでは、OpenAI 互換インターフェイスまたは DashScope API を介して Qwen-MT を呼び出す際の入出力パラメーターについて説明します。

参照: 機械翻訳 (Qwen-MT)

OpenAI 互換

シンガポールリージョン

SDK の base_urlhttps://dashscope-intl.aliyuncs.com/compatible-mode/v1

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

バージニアリージョン

SDK の base_urlhttps://dashscope-us.aliyuncs.com/compatible-mode/v1

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

北京リージョン

SDK の base_urlhttps://dashscope.aliyuncs.com/compatible-mode/v1

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

まず、API キーを作成し、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"),
    # 以下はシンガポールリージョンの base_url です。
    base_url="https://dashscope-intl.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,
        // 以下はシンガポールリージョンの base_url です。
        baseURL: "https://dashscope-intl.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://dashscope-intl.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"),
    # 以下はシンガポールリージョン用の base_url です。
    base_url="https://dashscope-intl.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,
        // 以下はシンガポールリージョンの base_url です。
        baseURL: "https://dashscope-intl.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 キーが異なります。以下はシンガポールリージョンのリクエストエンドポイントです。

curl -X POST https://dashscope.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"),
    # 以下はシンガポールリージョンの base_url です。
    base_url="https://dashscope-intl.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,
        // 以下はシンガポールリージョンの base_url です。
        baseURL: "https://dashscope-intl.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://dashscope-intl.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"),
    # 以下はシンガポールリージョンの base_url です。
    base_url="https://dashscope-intl.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,
        // 以下はシンガポールリージョン用の base_url です。
        baseURL: "https://dashscope-intl.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: "この文は Ali Cloud IT ドメインのものです。主にコンピューター関連のソフトウェア開発と使用方法に関係し、コンピューターのソフトウェアおよびハードウェアに関連する多くの用語が含まれています。翻訳する際は、専門的なトラブルシューティングの用語と文のパターンに注意してください。この IT ドメインのスタイルで翻訳してください。"
    }
});
console.log(JSON.stringify(completion));

curl

各リージョンでリクエストエンドポイントと API キーが異なります。以下はシンガポールリージョンのリクエストエンドポイントです。

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "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 です。

ニュークリアスサンプリングの確率のしきい値。生成されるテキストの多様性を制御します。

top_p の値が高いほど、テキストの多様性が高まります。top_p の値が低いほど、テキストの決定性が高まります。

有効値: (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 です。

モデル生成中の連続するシーケンスにおける繰り返しに対するペナルティ。repetition_penalty の値が高いほど、繰り返しが減少します。値が 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

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

次の 2 つのシナリオが適用されます:

  • 出力が完了すると、値は 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_tokenscompletion_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://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation

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

Python コード

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

Java コード

  • メソッド 1:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
  • メソッド 2:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://dashscope-intl.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://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 呼び出しに base_url を設定する必要はありません。デフォルト値は https://dashscope.aliyuncs.com/api/v1 です。

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

リクエストボディ

基本的な使用法

Python

import os
import dashscope

# 以下はシンガポールリージョンの base_url です。
dashscope.base_http_api_url = 'https://dashscope-intl.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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下はシンガポールリージョンの base_url です。
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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) {
        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://dashscope-intl.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

# 以下はシンガポールリージョンの base_url です。
dashscope.base_http_api_url = 'https://dashscope-intl.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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下はシンガポールリージョンの base_url です。
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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("health status of the body")
                .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://dashscope-intl.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

# 以下はシンガポールリージョン用の base_url です。
dashscope.base_http_api_url = 'https://dashscope-intl.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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下はシンガポールリージョンの base_url です。
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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://dashscope-intl.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

# 以下はシンガポールリージョンの base_url です。
dashscope.base_http_api_url = 'https://dashscope-intl.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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下はシンガポールリージョンの base_url です。
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.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) {
        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://dashscope-intl.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 呼び出しの場合、max_tokensparameters オブジェクトに配置します。

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 です。

ニュークリアスサンプリングの確率のしきい値。生成されるテキストの多様性を制御します。

top_p の値が高いほど、テキストの多様性が高まります。top_p の値が低いほど、テキストの決定性が高まります。

有効値: (0, 1.0]

temperature と top_p の両方が、生成されるテキストの多様性を制御します。どちらか一方のみを設定してください。

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

repetition_penalty float (任意) デフォルトは 1.0 です。

モデル生成中の連続するシーケンスにおける繰り返しに対するペナルティ。repetition_penalty の値が高いほど、繰り返しが減少します。値が 1.0 の場合はペナルティなしを示します。値は 0 より大きい必要がありますが、厳密な有効値はありません。

Java SDK では、パラメーターは repetitionPenalty です。HTTP 呼び出しの場合、repetition_penaltyparameters オブジェクトに追加します。

top_k integer (任意) デフォルトは 1 です。

生成中のサンプリングの候補セットのサイズ。たとえば、このパラメーターを 50 に設定すると、単一の生成で最もスコアの高い 50 個のトークンのみがランダムサンプリングの候補セットを形成するために使用されます。値が大きいほどランダム性が高まります。値が小さいほど決定性が高まります。値が None または 100 より大きい場合、top_k ポリシーは無効になり、top_p ポリシーのみが有効になります。

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

Java SDK では、パラメーターは topK です。HTTP 呼び出しを行う場合、top_kparameters オブジェクトに設定します。

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_codemessage の内容が含まれます。

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_tokensoutput_tokens の合計です。

エラーコード

モデルの呼び出しが失敗し、エラーメッセージが返された場合は、「エラーメッセージ」をご参照して問題を解決してください。