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

Alibaba Cloud Model Studio:機械翻訳 (Qwen-MT)

最終更新日:Jan 31, 2026

Qwen-MT は、Qwen3 をベースに機械翻訳用にファインチューニングされた大規模言語モデル (LLM) です。中国語、英語、日本語、韓国語、フランス語、スペイン語、ドイツ語、タイ語、インドネシア語、ベトナム語、アラビア語を含む 92 言語間の翻訳をサポートしています。また、複雑なアプリケーション シナリオにおける翻訳品質を向上させるため、用語介入、ドメインプロンプト、翻訳メモリなどの機能も提供しています。

仕組み

  1. 翻訳対象テキストを指定しますmessages 配列には、roleuser に設定された単一のメッセージを含める必要があります。このメッセージの content が翻訳対象のテキストとなります。

  2. 言語を設定しますsource_lang(ソース言語)および target_lang(ターゲット言語)を translation_options パラメーター内で設定します。サポートされている言語の一覧については、「サポートされる言語」をご参照ください。ソース言語を自動検出する場合は、source_langauto に設定します。

    ソース言語を明示的に指定することで、翻訳精度が向上します。
    カスタムプロンプトを使用して言語を設定することもできます。

以下の例では、OpenAI 互換および DashScope Python SDK を使用して Qwen-MT モデルを呼び出す方法を示します。

OpenAI 互換

# 依存関係をインポートし、クライアントを作成します...
completion = client.chat.completions.create(
    model="qwen-mt-flash",    # モデルを選択します
    # messages パラメーターには role が user に設定された単一のメッセージのみを含め、その content が翻訳対象テキストとなります。
    messages=[{"role": "user", "content": "No me reí después de ver este video"}],    
    # translation_options は標準的な OpenAI パラメーターではないため、extra_body パラメーター経由で渡す必要があります。
    extra_body={"translation_options": {"source_lang": "auto", "target_lang": "English"}},
)

DashScope

# 依存関係をインポートします...
response = dashscope.Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-mt-flash",  # モデルを選択します
    messages=[{"role": "user", "content": "No me reí después de ver este video"}],  # messages: 'role' は 'user'、'content' は翻訳対象テキストです。
    translation_options={"source_lang": "auto", "target_lang": "English"},  # 翻訳オプションを設定します。
    result_format="message"
)

制限事項

  • シングルターン翻訳のみ:このモデルは翻訳タスク専用に設計されており、マルチターン対話をサポートしていません。

  • システムメッセージ非対応system ロールのメッセージを使用してグローバルな動作を定義することはできません。translation_options パラメーター内で翻訳構成を定義してください。

モデル選択

  • 一般的なシナリオ向けには、qwen-mt-flash を選択できます。品質、速度、コストのバランスが取れており、増分ストリーミング出力をサポートしています。

  • 専門分野において最高の翻訳品質を求める場合は、qwen-mt-plus を選択できます。

  • シンプルかつリアルタイム性が求められるシナリオで最速の応答速度を求める場合は、qwen-mt-lite を選択できます。

以下の表は各モデルの比較です。

モデル

シナリオ

結果

速度

コスト

対応言語

増分ストリーミング出力のサポート

qwen-mt-plus

専門分野、正式なドキュメント、学術論文、技術レポートなど、高品質な翻訳が求められるシナリオ

最高

標準

92

未サポート

qwen-mt-flash

汎用的な利用における最適な選択肢。Web サイト/アプリのコンテンツ、商品説明、日常会話、ブログ投稿などのシナリオに適しています

良好

高速

92

サポート

qwen-mt-turbo

このモデルは今後アップデートされません。代わりに flash を使用してください。

普通

高速

92

未サポート

qwen-mt-lite

リアルタイムチャットや弾幕翻訳など、シンプルかつ遅延の影響を受けやすいシナリオ

基本

最速

最低

31

サポート

モデルのコンテキスト長および料金に関する詳細情報については、「Qwen-MT」をご参照ください。同時リクエスト制限に関する情報については、「Qwen 翻訳」をご参照ください。

クイックスタート

このセクションでは、"No me reí después de ver este video" を英語に翻訳する簡単な例を示します。

API キーを取得し、API キーを環境変数として設定する必要があります。OpenAI SDK または DashScope SDK を使用して呼び出しを行う場合は、SDK をインストールする必要もあります。

OpenAI 互換

リクエスト例

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Alibaba Cloud Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    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)
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 実行前にこのコメントを削除してください ====

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

応答例

I didn't laugh after watching this video. 

DashScope

リクエスト例

重要

DashScope Java SDK はバージョン 2.20.6 以降である必要があります。

import os
import dashscope

# 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
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-turbo",  # この例では qwen-mt-turbo を使用しています。必要に応じて他のモデル名に置き換えてください。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// 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 {
        // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
        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()
                // 環境変数が設定されていない場合、次の行を Alibaba Cloud 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);
        }
    }
}
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 実行前にこのコメントを削除してください ====

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-turbo",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'

応答例

I didn't laugh after watching this video. 

ストリーミング出力

ストリーミング出力により、翻訳内容がリアルタイムで返され、ユーザーの待ち時間が短縮されます現在、qwen-mt-flash および qwen-mt-lite のみが増分ストリーミング出力をサポートしており、各応答には新しく生成されたコンテンツのみが含まれます。incremental_output パラメーターを使用してこの機能を有効にできます。qwen-mt-plus および qwen-mt-turbo モデルは、非増分ストリーミング出力のみをサポートしています。各応答にはそれまでに生成されたすべてのシーケンスが返され、最終応答には完全な結果が含まれます。詳細については、「ストリーミング出力」をご参照ください。

OpenAI 互換

リクエスト例

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    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-flash",
    messages=messages,
    stream=True,
    stream_options={"include_usage": True},
    extra_body={"translation_options": translation_options},
)
for chunk in completion:
    if chunk.choices:
        content = chunk.choices[0].delta.content or ""
        print(content, end="", flush=True)
    else:
        print("="*20+"Usage"+"="*20)
        print(chunk.usage)
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 実行前にこのコメントを削除してください ====

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

応答例

I didn’t laugh after watching this video.
====================Usage====================
CompletionUsage(completion_tokens=9, prompt_tokens=56, total_tokens=65, completion_tokens_details=None, prompt_tokens_details=None)

DashScope

リクエスト例

import os
import dashscope

# 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
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-flash",  # この例では qwen-mt-turbo を使用しています。必要に応じて他のモデル名に置き換えてください。
    messages=messages,
    result_format='message',
    stream=True,
    # 増分出力を取得するには incremental_output を True に設定します。推奨されます。現在、qwen-mt-flash のみがこの機能をサポートしています。
    incremental_output=True,
    translation_options=translation_options
)
for chunk in response:
    print(chunk.output.choices[0].message.content, end="", flush=True)
// DashScope SDK はバージョン 2.20.6 以降である必要があります。
import java.lang.System;
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 java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.Flowable;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static void handleGenerationResult(GenerationResult message) {
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();
        System.out.print(content);
    }
    public static void streamCallWithMessage(Generation gen, Message userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException {
        GenerationParam param = buildGenerationParam(userMsg);
        Flowable<GenerationResult> result = gen.streamCall(param);
        result.blockingForEach(message -> handleGenerationResult(message));
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .build();
        return GenerationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-mt-flash")
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                // 増分出力を有効にします。qwen-mt-flash のみがサポートしています。
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void main(String[] args) {
        try {
            // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
            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();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException  e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 実行前にこのコメントを削除してください ====

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" \
-H "X-DashScope-SSE: enable" \
-d '{
  "model": "qwen-mt-flash",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
  },
  "incremental_output":true
}'

応答例

I didn't laugh after watching this video. 
qwen-mt-plus および qwen-mt-turbo は増分ストリーミング出力をサポートしていません。

翻訳品質の向上

日常会話などのシンプルなユースケースでは、標準的な翻訳で十分です。ただし、専門的または要求の厳しい翻訳タスクでは、以下の問題が発生することがあります。

  • 用語の一貫性の欠如:製品名や業界用語が誤って翻訳される。

  • スタイルの不一致:翻訳されたテキストのスタイルが、法務やマーケティングなどの特定のドメインの基準を満たしていない。

これらの問題を解決するために、用語介入、翻訳メモリ、ドメインプロンプトを利用できます。

用語介入

ブランド名、製品名、技術用語を含むテキストの翻訳精度と一貫性を確保するには、terms フィールドに用語集を指定できます。これにより、モデルは指定された翻訳を使用するよう指示されます。

用語を定義して渡す手順は以下のとおりです。

  1. 用語を定義します

    JSON 配列を作成し、terms フィールドに割り当てます。配列内の各オブジェクトは、以下の形式で用語を表します。

    {
        "source": "term",
        "target": "pre-translated term"
    }
  2. 規約への同意

    translation_options パラメーターを使用して、定義した terms 配列を渡します。

OpenAI 互換

リクエスト例

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    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."
    }
]

# --- 最初のリクエスト:terms パラメーターなし ---
print("--- [terms なしの翻訳結果] ---")
translation_options_without_terms = {
    "source_lang": "auto",
    "target_lang": "English"
}

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

print("\n" + "="*50 + "\n") # 比較用の区切り

# --- 2 回目のリクエスト:terms パラメーターあり ---
print("--- [terms ありの翻訳結果] ---")
translation_options_with_terms = {
    "source_lang": "auto",
    "target_lang": "English",
    "terms": [
        {
            "source": "biosensor",
            "target": "biological sensor"
        },
        {
            "source": "estado de salud del cuerpo",
            "target": "health status of the body"
        }
    ]
}

completion_with_terms = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options_with_terms
    }
)
print(completion_with_terms.choices[0].message.content)
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 実行前にこのコメントを削除してください ====

curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "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": "estado de salud del cuerpo",
        "target": "health status of the body"
      }
    ]
  }
}'

応答例

用語を追加すると、翻訳結果が渡した用語「biological sensor」および「health status of the body」と一致します。

--- [用語なしの翻訳結果] ---
この一連のバイオセンサーは新素材のグラフェンを使用しており、化学元素を標的物質としています。その高感度な「嗅覚」により、人の健康状態をより深く、より正確に反映することが可能です。

==================================================

--- [用語ありの翻訳結果] ---
このバイオセンサーは、グラフェンという新素材を使用しています。そのターゲットは化学元素であり、高感度な「嗅覚」によって、身体の健康状態をより深く、より正確に反映することができます。

DashScope

リクエスト例

import os
import dashscope

# 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えます。
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": "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-turbo",  # この例では qwen-mt-turbo を使用しています。必要に応じて、別のモデル名に置き換えることができます。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// 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 {
        // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
        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("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);
    }
}
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 実行前にこのコメントを削除してください ====

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-turbo",
  "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"
        }
      ]
    }
  }
}'

応答例

This biological sensor uses graphene, a new material, and its target is chemical elements. Its sensitive "nose" can more deeply and accurately reflect the health status of the human body. 

翻訳メモリ

モデルに特定の翻訳スタイルや文のパターンを使用するよう指示するには、tm_list フィールドにソースとターゲットの文ペアを例として提供できます。これにより、モデルはこれらの例のスタイルを模倣して現在の翻訳タスクを実行します。

  1. 翻訳メモリを定義します

    tm_list という名前の JSON 配列を作成します。配列内の各 JSON オブジェクトには、ソース文とその対応する翻訳文が以下の形式で含まれます。

    {
        "source": "source statement",
        "target": "translated statement"
    }
  2. 翻訳メモリを渡します

    translation_options パラメーターを使用して、翻訳メモリ配列を渡します。

以下のコードは、翻訳メモリ機能の使用方法を示しています。

OpenAI 互換

リクエスト例

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    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",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 実行前にこのコメントを削除してください ====

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

応答例

You can run the following command to view the version of Thrift that is installed:

DashScope

リクエスト例

import os
import dashscope

# 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
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-turbo",  # この例では qwen-mt-turbo を使用しています。必要に応じて他のモデル名に置き換えてください。
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// 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 {
        // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
        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);
    }
}
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 実行前にこのコメントを削除してください ====

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-turbo",
  "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:"}
      ]
  }
}'

応答例

You can use the following commands to check the version information of thrift installed; 

ドメインプロンプト

翻訳スタイルを特定のドメインに合わせるには、translation_options パラメーターを使用してドメインプロンプトを渡せます。たとえば、法務や政府機関向けのドメインでは正式な文体を、ソーシャルメディア向けでは口語的な文体を使用します。

重要

ドメインプロンプトは現在、英語でのみサポートされています。

OpenAI 互換

リクエスト例

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    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."
    }
]

# --- 最初のリクエスト:domains パラメーターなし ---
print("--- [domains なしの翻訳結果] ---")
translation_options_without_domains = {
    "source_lang": "auto",
    "target_lang": "English",
}

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

print("\n" + "="*50 + "\n") # 比較用の区切り

# --- 2 回目のリクエスト:domains パラメーターあり ---
print("--- [domains ありの翻訳結果] ---")
translation_options_with_domains = {
    "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."
}

completion_with_domains = client.chat.completions.create(
    model="qwen-mt-plus",
    messages=messages,
    extra_body={
        "translation_options": translation_options_with_domains
    }
)
print(completion_with_domains.choices[0].message.content)
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 実行前にこのコメントを削除してください ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "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."
  }
}'

応答例

--- [ドメインなしの翻訳結果] ---
2 番目の SELECT 文は、LIMIT 句がない場合に最初の SELECT 文が返す行数を示す数値を返します。

==================================================

--- [ドメインありの翻訳結果] ---
2 番目の SELECT 文は、LIMIT 句が含まれていなかった場合に最初の SELECT 文が返したであろう行数を示す数値を返します。

DashScope

リクエスト例

import os
import dashscope

# 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/api/v1 に置き換えます。
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-turbo",  
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// 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 {
        // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
        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"))
                // 注:qwen-mt-lite はドメインプロンプトをサポートしていません
                .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);
    }
}
# ======= 重要 =======
# 北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 実行前にこのコメントを削除してください ====

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-turbo",
  "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."}
  }
}'

応答例

The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause. 

カスタムプロンプト

Qwen-MT では、カスタムプロンプトを使用して言語やスタイルなどの詳細を指定できます。この方法は translation_options パラメーターと相互排他です。両方を使用した場合、translation_options が有効にならない可能性があります。

最適な翻訳結果を得るには、translation_options を使用して翻訳設定を構成することを推奨します。

以下の例は、法務ドメインにおけるスペイン語から英語への翻訳を示しています。

OpenAI 互換

import os
from openai import OpenAI

client = OpenAI(
    # 環境変数が設定されていない場合、次の行を Alibaba Cloud Model Studio API キーに置き換えます:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
prompt_template = """
# Role
You are a professional legal translation expert, proficient in both Spanish and English, and you are especially skilled at handling commercial contracts and legal documents.

# Task
I need you to translate the following Spanish legal text into professional, accurate, and formal English.

# Translation Requirements
1.  **Fidelity to the Original**: Strictly translate according to the meaning and legal intent of the original text. Do not add or omit information.
2.  **Precise Terminology**: Use standard legal terms common in the Common Law system. For example, "甲方" should be translated as "Party A", "乙方" as "Party B", and "不可抗力" as "Force Majeure".
3.  **Formal Tone**: Maintain the rigorous, objective, and formal style inherent in legal documents.
4.  **Clarity of Language**: The translation must be clear, unambiguous, and conform to the expressive conventions of English legal writing.
5.  **Format Preservation**: Retain the paragraphs, numbering, and basic format of the original text.

# Text to be Translated
{text_to_translate}
"""

# --- 2. 翻訳対象の法務テキストを準備します ---
chinese_legal_text = "Este contrato entrará en vigor a partir de la fecha en que ambas partes lo firmen y sellen, y tendrá una vigencia de un año."
final_prompt = prompt_template.format(text_to_translate=chinese_legal_text)

# --- 3. messages を構築します ---
messages = [{"role": "user", "content": final_prompt}]

# --- 4. API リクエストを開始します ---
completion = client.chat.completions.create(model="qwen-mt-plus", messages=messages)

# --- 5. モデルの翻訳結果を出力します ---
translation_result = completion.choices[0].message.content
print(translation_result)
import OpenAI from 'openai';

const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 北京リージョンのモデルを使用する場合は、base_url を https://dashscope.aliyuncs.com/compatible-mode/v1 に置き換えてください。
    baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
});

const promptTemplate = `
# 役割
あなたはスペイン語と英語の両方に精通したプロフェッショナルな法律翻訳専門家であり、ビジネス契約書および法律文書を専門としています。

# タスク
以下のスペイン語の法律文書を、プロフェッショナルで正確かつフォーマルな英語に翻訳してください。

# 翻訳要件
1.  **原文忠実性**: 原文の意味および法的意図に厳密に従って翻訳してください。情報を追加または省略してはなりません。
2.  **正確な用語**: コモン・ロー制度で一般的な標準的な法律用語を使用してください。例えば、「甲方」は「Party A」、「乙方」は「Party B」、「不可抗力」は「Force Majeure」と翻訳してください。
3.  **フォーマルなトーン**: 法律文書に内在する厳密で客観的かつフォーマルなトーンを維持してください。
4.  **明確性**: 翻訳文は明確で曖昧さがなく、英語の法律文書における表現規則に準拠している必要があります。
5.  **フォーマットの保持**: 原文の段落、番号付け、基本的なフォーマットを保持してください。

# 翻訳対象テキスト
{text_to_translate}
`;

const spanishLegalText = "This Contract shall become effective from the date of signature and seal by both parties and shall be valid for a period of one year.";
const finalPrompt = promptTemplate.replace('{text_to_translate}', spanishLegalText);

const messages = [{"role": "user", "content": finalPrompt}];

async function main() {
    const completion = await client.chat.completions.create({
        model: "qwen-mt-plus",
        messages: messages
    });

    const translationResult = completion.choices[0].message.content;
    console.log(translationResult);
}

main();

応答例

This Contract shall become effective from the date on which both parties sign and affix their seals, and its term of validity shall be one year.

DashScope

リクエスト例

import os
import dashscope

# 北京リージョンのモデルを使用する場合、base_url を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
prompt_template = """
# Role
You are a professional legal translation expert, proficient in both Spanish and English, with special expertise in handling business contracts and legal documents.

# Task
I need you to translate the following Spanish legal text into professional, accurate, and formal English.

# Translation Requirements
1.  **Fidelity to the Original**: Strictly translate according to the meaning and legal intent of the original text. Do not add or omit any information.
2.  **Precise Terminology**: Use standard legal terms common to the Common Law system. For example, "甲方" should be translated as "Party A", "乙方" as "Party B", and "不可抗力" as "Force Majeure".
3.  **Formal Tone**: Maintain the rigorous, objective, and formal style inherent in legal documents.
4.  **Clear Phrasing**: The translation must be clear, unambiguous, and conform to the conventions of English legal writing.
5.  **Preserve Formatting**: Maintain the paragraphs, numbering, and basic format of the original text.

# Text to be Translated
{text_to_translate}
"""

# --- 2. 翻訳対象の法務テキストを準備します ---
chinese_legal_text = "This Contract shall become effective from the date of signature and seal by both parties and shall be valid for a period of one year."
final_prompt = prompt_template.format(text_to_translate=chinese_legal_text)

# --- 3. messages を構築します ---
messages = [
    {
        "role": "user",
        "content": final_prompt
    }
]

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',
)
print(response.output.choices[0].message.content)
// 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.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 {
        // 以下はシンガポールリージョン用の URL です。北京リージョンのモデルを使用する場合、URL を次のように置き換えます:https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        String promptTemplate = "# Role\n" +
                "You are a professional legal translation expert, proficient in both Spanish and English, specializing in business contracts and legal documents.\n\n" +
                "# Task\n" +
                "I need you to translate the following Spanish legal text into professional, accurate, and formal English.\n\n" +
                "# Translation Requirements\n" +
                "1.  **Fidelity to the Original**: Translate strictly according to the meaning and legal intent of the original text. Do not add or omit information.\n" +
                "2.  **Precise Terminology**: Use standard legal terms common in the Common Law system. For example, \"甲方\" should be translated as \"Party A\", \"乙方\" as \"Party B\", and \"不可抗力\" as \"Force Majeure\".\n" +
                "3.  **Formal Tone**: Maintain the rigorous, objective, and formal tone inherent in legal documents.\n" +
                "4.  **Clarity**: The translation must be clear, unambiguous, and conform to the expressive conventions of English legal writing.\n" +
                "5.  **Format Preservation**: Retain the paragraphs, numbering, and basic format of the original text.\n\n" +
                "# Text to Translate\n" +
                "{text_to_translate}";

        String spanishLegalText = "This Contract shall become effective from the date of signature and seal by both parties and shall be valid for a period of one year.";
        String finalPrompt = promptTemplate.replace("{text_to_translate}", spanishLegalText);

        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content(finalPrompt)
                .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)
                .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();
        }
        }
}

応答例

This Contract shall become effective from the date on which both parties sign and affix their seals, and its term of validity shall be one year.

本番環境に適用

  • 入力トークン数を制御します

    Qwen-MT モデルの最大入力制限は 8,192 トークンです。長いコンテンツを扱う場合は、以下の戦略を検討して入力トークン数を制御してください。

    • セグメント単位で翻訳します:長いテキストを翻訳する際は、セグメント単位で処理します。文字数ではなく、段落や完全な文などの意味単位でテキストを分割します。これにより、コンテキストの一貫性が保たれ、翻訳品質が向上します。

    • 最も関連性の高い参照コンテンツを提供します:用語、翻訳メモリ、ドメインプロンプトは、入力プロンプトにトークンとして追加されます。トークン使用量を最適化するには、現在のタスクに最も関連性の高い参照コンテンツのみを提供します。大規模で汎用的なリストの使用は避けてください。

  • シナリオに基づいて source_lang を設定します

    • ソース言語が不確かな場合(たとえば、多言語テキストを含むソーシャルチャットのシナリオなど)、source_langauto に設定します。これにより、モデルが自動的にソース言語を識別します。

    • 言語が固定されており、高精度が求められるシナリオ(たとえば、技術ドキュメントや操作マニュアルなど)では、常に source_lang を明示的に指定します。ソース言語を明示的に定義することで、翻訳精度が向上します。

サポートされる言語

リクエストを送信する際は、以下の表の英語名またはコードを使用してください。

ソース言語が不明な場合は、source_lang パラメーターを auto に設定して自動検出を利用できます。

qwen-mt-plus/flash/turbo でサポートされる言語 (92)

言語

英語名

コード

英語

English

en

簡体字中国語

Chinese

zh

繁体字中国語

Traditional Chinese

zh_tw

ロシア語

Russian

ru

日本語

Japanese

ja

韓国語

Korean

ko

スペイン語

Spanish

es

フランス語

French

fr

ポルトガル語

Portuguese

pt

ドイツ語

German

de

イタリア語

Italian

it

タイ語

Thai

th

ベトナム語

Vietnamese

vi

インドネシア語

Indonesian

id

マレー語

Malay

ms

アラビア語

Arabic

ar

ヒンディー語

Hindi

hi

ヘブライ語

Hebrew

he

ビルマ語

Burmese

my

タミル語

Tamil

ta

ウルドゥー語

Urdu

ur

ベンガル語

Bengali

bn

ポーランド語

Polish

pl

オランダ語

Dutch

nl

ルーマニア語

Romanian

ro

トルコ語

Turkish

tr

クメール語

Khmer

km

ラオス語

Lao

lo

広東語

Cantonese

yue

チェコ語

Czech

cs

ギリシャ語

Greek

el

スウェーデン語

Swedish

sv

ハンガリー語

Hungarian

hu

デンマーク語

Danish

da

フィンランド語

Finnish

fi

ウクライナ語

Ukrainian

uk

ブルガリア語

Bulgarian

bg

セルビア語

Serbian

sr

テルグ語

Telugu

te

アフリカーンス語

Afrikaans

af

アルメニア語

Armenian

hy

アッサム語

Assamese

as

アストゥリアス語

Asturian

ast

バスク語

Basque

eu

ベラルーシ語

Belarusian

be

ボスニア語

Bosnian

bs

カタロニア語

Catalan

ca

セブアノ語

Cebuano

ceb

クロアチア語

Croatian

hr

エジプト・アラビア語

Egyptian Arabic

arz

エストニア語

Estonian

et

ガリシア語

Galician

gl

グルジア語

Georgian

ka

グジャラート語

Gujarati

gu

アイスランド語

Icelandic

is

ジャワ語

Javanese

jv

カンナダ語

Kannada

kn

カザフ語

Kazakh

kk

ラトビア語

Latvian

lv

リトアニア語

Lithuanian

lt

ルクセンブルク語

Luxembourgish

lb

マケドニア語

Macedonian

mk

マイティリー語

Maithili

mai

マルタ語

Maltese

mt

マラーティー語

Marathi

mr

メソポタミア・アラビア語

Mesopotamian Arabic

acm

モロッコ・アラビア語

Moroccan Arabic

ary

ナジュド・アラビア語

Najdi Arabic

ars

ネパール語

Nepali

ne

北アゼルバイジャン語

North Azerbaijani

az

北レバント・アラビア語

North Levantine Arabic

apc

北部ウズベク語

Northern Uzbek

uz

ノルウェー語(ブークモール)

Norwegian Bokmål

nb

ノルウェー語(ニーノシュク)

Norwegian Nynorsk

nn

オック語

Occitan

oc

オリヤー語

Odia

or

パンガシナン語

Pangasinan

pag

シチリア語

Sicilian

scn

シンディー語

Sindhi

sd

シンハラ語

Sinhala

si

スロバキア語

Slovak

sk

スロベニア語

Slovenian

sl

南レバント・アラビア語

South Levantine Arabic

ajp

スワヒリ語

Swahili

sw

タガログ語

Tagalog

tl

タイズ・アデニ・アラビア語

Ta’izzi-Adeni Arabic

acq

トスカ・アルバニア語

Tosk Albanian

sq

チュニジア・アラビア語

Tunisian Arabic

aeb

ヴェネト語

Venetian

vec

Valaisan

ワライ語

WAR

ウェールズ語

ウェールズ語

cy

西ペルシア語

西ペルシア語

fa

qwen-mt-lite でサポートされる言語 (31)

言語

英語名

コード

英語

English

en

簡体字中国語

Chinese

zh

繁体字中国語

Traditional Chinese

zh_tw

ロシア語

Russian

ru

日本語

Japanese

ja

韓国語

Korean

ko

スペイン語

Spanish

es

フランス語

French

fr

ポルトガル語

Portuguese

pt

ドイツ語

German

de

イタリア語

Italian

it

タイ語

Thai

th

ベトナム語

Vietnamese

vi

インドネシア語

Indonesian

id

マレー語

Malay

ms

アラビア語

Arabic

ar

ヒンディー語

Hindi

hi

ヘブライ語

Hebrew

he

ウルドゥー語

Urdu

ur

ベンガル語

Bengali

bn

ポーランド語

Polish

pl

オランダ語

Dutch

nl

トルコ語

Turkish

tr

クメール語

Khmer

km

チェコ語

Czech

cs

スウェーデン語

Swedish

sv

ハンガリー語

Hungarian

hu

デンマーク語

Danish

da

フィンランド語

Finnish

fi

タガログ語

Tagalog

tl

ペルシア語

Persian

fa

API リファレンス

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