Qwen-MT は、Qwen3 をベースにファインチューニングされた機械翻訳モデルです。中国語、英語、日本語、韓国語、フランス語、スペイン語、ドイツ語、タイ語、インドネシア語、ベトナム語、アラビア語など、92 言語をサポートしており、用語介入、ドメインプロンプト、翻訳メモリなどの機能により、翻訳品質を制御できます。
仕組み
-
翻訳対象テキストを指定します:
messages配列には、roleがuserに設定されたメッセージを 1 つだけ含める必要があります。このメッセージのcontentが翻訳対象のテキストとなります。 -
言語を設定します:
translation_optionsパラメーター内で、ソース言語 (source_lang) およびターゲット言語 (target_lang) を指定します。サポートされている言語の一覧については、「サポート言語」をご参照ください。ソース言語を自動検出させる場合は、source_langをautoに設定します。ソース言語を明示的に指定することで、翻訳精度が向上します。
カスタムプロンプト を使用して言語を設定することもできます。
以下の例では、OpenAI 互換および 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"
)
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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-mt-turbo",
# 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
import os
import dashscope
# base_url はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
response = dashscope.Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-mt-turbo",
# messages パラメーターには role が "user" に設定されたメッセージを 1 つだけ含め、その content が翻訳対象テキストとなる必要があります。
messages=[
{
"role": "user",
"content": "No me reí después de ver este video"
}
],
# 翻訳オプションを設定。
translation_options={
"source_lang": "auto",
"target_lang": "English",
}
result_format="message"
)
print(response.output.choices[0].message.content)
translation_options パラメーターを使用して、用語介入、翻訳メモリ、ドメインプロンプト などの高度な翻訳機能にアクセスできます。
制限事項
-
シングルターン翻訳のみ:Qwen-MT は翻訳専用に設計されており、マルチターン対話をサポートしていません。
-
システムメッセージ非対応:
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 翻訳モデル」をご参照ください。
クイックスタート
このセクションでは、"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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English"
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= 重要 =======
# URL はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("No me reí después de ver este video")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.build();
GenerationParam param = GenerationParam.builder()
// 環境変数が設定されていない場合は、次の行を 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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "No me reí después de ver este video"}]
translation_options = {"source_lang": "auto", "target_lang": "English"}
completion = client.chat.completions.create(
model="qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("No me reí después de ver este video").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}# ======= 重要 =======
# URL はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-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 は増分ストリーミング出力をサポートしていません。
翻訳品質の向上
基本的な翻訳は、カジュアルなコミュニケーションなど日常的なユースケースでは十分に機能します。ただし、専門的または重要な翻訳タスクでは、以下の特定の課題に直面する可能性があります。
-
用語の一貫性の欠如:製品名や業界固有の用語が、文章間で誤って翻訳されたり、一貫性がなかったりします。
-
スタイルの不一致:翻訳されたテキストが、法務やマーケティングなどの特定のドメインで期待されるトーンや規則に合致しません。
Qwen-MT は、これらの課題に対処するために、用語介入、翻訳メモリ、ドメインプロンプトの 3 つの機能を提供します。
用語介入
terms フィールドに用語集を指定することで、ブランド名、製品名、技術用語が毎回一貫して翻訳されるように保証できます。
用語集を定義して渡す手順は以下のとおりです。
-
用語を定義します
JSON 配列を作成し、
termsフィールドに割り当てます。配列内の各オブジェクトは、ソース用語とその必須翻訳をマッピングします。{ "source": "term", "target": "pre-translated term" } -
規約に同意する
terms配列を含んだ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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
# --- 最初のリクエスト: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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。使用するリージョンに基づいて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.")
.build();
Term term1 = Term.builder()
.source("biosensor")
.target("biological sensor")
.build();
Term term2 = Term.builder()
.source("estado de salud del cuerpo")
.target("health status of the body")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.terms(Arrays.asList(term1, term2))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= 重要 =======
# URL はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-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 フィールドにソース-ターゲットの文ペアを例として提供します。モデルはこれらの参照ペアのスタイルを学習し、現在の翻訳に適用します。これは、大規模なドキュメントセット全体で一貫性を維持したり、組織の確立された執筆規則に適合させたりする場合に役立ちます。
-
翻訳メモリを定義します
tm_listという名前の JSON 配列を作成します。各オブジェクトは、ソース文とその参照翻訳をペアにします。{ "source": "source statement", "target": "translated statement" } -
翻訳メモリを渡します
翻訳メモリ配列を含んだ
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 はリージョンによって異なります。使用するリージョンに基づいて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= 重要 =======
# URL はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]}
response = dashscope.Generation.call(
# 環境変数が設定されていない場合は、次の行を Model Studio API キーに置き換えます:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("El siguiente comando muestra la información de la versión de Thrift instalada.")
.build();
Tm tm1 = Tm.builder()
.source("Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:")
.target("You can use one of the following methods to query the engine version of a cluster:")
.build();
Tm tm2 = Tm.builder()
.source("La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.")
.target("The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website.")
.build();
Tm tm3 = Tm.builder()
.source("Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:")
.target("You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.tmList(Arrays.asList(tm1, tm2, tm3))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= 重要 =======
# URL はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
# --- 最初のリクエスト: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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。使用するリージョンに基づいて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
response = dashscope.Generation.call(
# 環境変数を設定していない場合は、次の行をご自身の Model Studio API キーに置き換えてください (例: api_key="sk-xxx")。
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// 注意: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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
# === 実行前にこのコメントを削除してください ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
prompt_template = """
# 役割
あなたはスペイン語と英語の両方に精通したプロフェッショナルな法務翻訳専門家であり、特に商業契約および法務文書の取り扱いに長けています。
# タスク
以下のスペイン語の法務テキストを、プロフェッショナルで正確かつフォーマルな英語に翻訳する必要があります。
# 翻訳要件
1. **原文忠実性**:原文の意味および法的意図に厳密に従って翻訳してください。情報を追加または省略しないでください。
2. **用語の正確性**:コモン・ロー制度で一般的な標準的な法的用語を使用してください。たとえば、「甲方」は「Party A」、「乙方」は「Party B」、「不可抗力」は「Force Majeure」と翻訳します。
3. **フォーマルなトーン**:法務文書に内在する厳密で客観的かつフォーマルなスタイルを維持してください。
4. **言語の明確性**:翻訳は明確で曖昧さがなく、英語の法務文書作成における表現規則に準拠している必要があります。
5. **フォーマットの保持**:原文の段落、番号付け、基本的なフォーマットを保持してください。
# 翻訳対象テキスト
{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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
prompt_template = """
# 役割
あなたはスペイン語と英語の両方に精通したプロフェッショナルな法務翻訳専門家であり、ビジネス契約および法務文書の取り扱いに特に精通しています。
# タスク
以下のスペイン語の法務テキストを、プロフェッショナルで正確かつフォーマルな英語に翻訳する必要があります。
# 翻訳要件
1. **原文忠実性**:原文の意味および法的意図に厳密に従って翻訳してください。情報を追加または省略しないでください。
2. **用語の正確性**:コモン・ロー制度で一般的な標準的な法的用語を使用してください。たとえば、「甲方」は「Party A」、「乙方」は「Party B」、「不可抗力」は「Force Majeure」と翻訳します。
3. **フォーマルなトーン**:法務文書に内在する厳密で客観的かつフォーマルなスタイルを維持してください。
4. **明確な表現**:翻訳は明確で曖昧さがなく、英語の法務文書作成の規則に準拠している必要があります。
5. **フォーマットの保持**:原文の段落、番号付け、基本的なフォーマットを保持してください。
# 翻訳対象テキスト
{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 はリージョンによって異なります。ご利用のリージョンに応じて更新してください。
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
String promptTemplate = "# 役割\n" +
"あなたはスペイン語と英語の両方に精通したプロフェッショナルな法務翻訳専門家であり、ビジネス契約および法務文書を専門としています。\n\n" +
"# タスク\n" +
"以下のスペイン語の法務テキストを、プロフェッショナルで正確かつフォーマルな英語に翻訳する必要があります。\n\n" +
"# 翻訳要件\n" +
"1. **原文忠実性**:原文の意味および法的意図に厳密に従って翻訳してください。情報を追加または省略しないでください。\n" +
"2. **用語の正確性**:コモン・ロー制度で一般的な標準的な法的用語を使用してください。たとえば、「甲方」は「Party A」、「乙方」は「Party B」、「不可抗力」は「Force Majeure」と翻訳します。\n" +
"3. **フォーマルなトーン**:法務文書に内在する厳密で客観的かつフォーマルなトーンを維持してください。\n" +
"4. **明確性**:翻訳は明確で曖昧さがなく、英語の法務文書作成における表現規則に準拠している必要があります。\n" +
"5. **フォーマットの保持**:原文の段落、番号付け、基本的なフォーマットを保持してください。\n\n" +
"# 翻訳対象テキスト\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_langをautoに設定します。モデルが自動的に言語を識別します。 -
ソース言語が既知で精度が重要である場合(たとえば、技術ドキュメントや操作マニュアルなど)は、常に
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」をご参照ください。