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

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

最終更新日:Jan 05, 2026

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

仕組み

  1. 翻訳するテキストの提供messages 配列には、roleuser に設定されたメッセージを 1 つだけ含める必要があります。このメッセージの content が翻訳対象のテキストです。

  2. 言語の設定translation_options パラメーターで、翻訳元言語 (source_lang) と翻訳先言語 (target_lang) を設定します。対応言語のリストについては、「対応言語」をご参照ください。翻訳元言語を自動検出するには、source_langauto に設定します。

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

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

OpenAI 互換

# 依存関係をインポートし、クライアントを作成します...
completion = client.chat.completions.create(
    model="qwen-mt-flash",    # モデルを選択
    # messages パラメーターには、role が user のメッセージを 1 つだけ含める必要があります。その 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

一般的な利用に最適。ウェブサイト/アプリのコンテンツ、製品説明、日常的なコミュニケーション、ブログ投稿などのシナリオに適しています

92

対応

対応

qwen-mt-turbo

代替オプション。flash モデルの方が品質と機能が優れています。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."
    }
]

# --- 1回目のリクエスト: 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-intl.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 パラメーターを使用してドメインプロンプトを渡します。たとえば、法律や政府関連のドメインの翻訳はフォーマルであるべきですが、ソーシャルメディアの翻訳は口語的であるべきです。

現在、qwen-mt-lite はドメインプロンプトをサポートしていません。
重要

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

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."
    }
]

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

completion_without_domains = client.chat.completions.create(
    model="qwen-mt-plus", # 注意: qwen-mt-lite はドメインプロンプトをサポートしていません
    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 文は、最初の SELECT 文に LIMIT 句がなかった場合に返される行数を示す数値を返します。

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

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

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",  # 注: qwen-mt-lite はドメインプロンプティングをサポートしていません
    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
あなたは、スペイン語と英語の両方に堪能なプロの法律翻訳専門家であり、商業契約書や法律文書の取り扱いに特に優れています。

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

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

# 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 = [{"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 = `
# Role
あなたは、スペイン語と英語の両方に堪能なプロの法律翻訳専門家であり、商業契約書や法律文書の取り扱いに特化しています。

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

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

# Text to Translate
{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
あなたは、スペイン語と英語の両方に堪能なプロの法律翻訳専門家であり、商業契約書や法律文書の取り扱いに特に優れています。

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

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

# 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 = [
    {
        "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" +
                "あなたは、スペイン語と英語の両方に堪能なプロの法律翻訳専門家であり、商業契約書や法律文書の取り扱いに特化しています。\n\n" +
                "# Task\n" +
                "以下のスペイン語の法律文書を、プロフェッショナルで正確、かつフォーマルな英語に翻訳してください。\n\n" +
                "# Translation Requirements\n" +
                "1.  **原文への忠実性**: 原文の意味と法的な意図に厳密に従って翻訳してください。情報を追加したり省略したりしないでください。\n" +
                "2.  **正確な用語**: コモンロー制度で一般的に使用される標準的な法律用語を使用してください。例えば、「甲方」は「Party A」、「乙方」は「Party B」、「不可抗力」は「Force Majeure」と翻訳してください。\n" +
                "3.  **フォーマルなトーン**: 法律文書に固有の厳格で客観的、かつフォーマルなスタイルを維持してください。\n" +
                "4.  **明確な表現**: 翻訳は明確で曖昧さがなく、英語の法律文書の慣習に準拠している必要があります。\n" +
                "5.  **フォーマットの維持**: 原文の段落、番号付け、基本的なフォーマットを保持してください。\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();
        }
        }
}

応答例

本契約は、両当事者が署名捺印した日から効力を生じ、その有効期間は1年間とする。

本番環境への適用

  • 入力トークン数の制御

    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

ヴァレー語

Waray

war

ウェールズ語

Welsh

cy

西ペルシャ語

Western Persian

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 翻訳モデル」をご参照ください。