Qwen-MT は Qwen3 からファインチューニングされた機械翻訳モデルです。中国語、英語、日本語、韓国語、フランス語、スペイン語、ドイツ語、タイ語、インドネシア語、ベトナム語、アラビア語を含む 92 の言語をサポートし、用語介入、ドメインプロンプト、翻訳メモリを提供して翻訳品質を制御します。
仕組み
-
翻訳するテキストの指定:
messages配列には、そのroleをuserに設定した単一のメッセージを含める必要があります。このメッセージのcontentは、翻訳するテキストです。 -
言語の設定:
translation_optionsパラメーターでソース言語 (source_lang) とターゲット言語 (target_lang) を指定します。サポートされている言語のリストについては、「サポートされている言語」をご参照ください。モデルがソース言語を自動的に検出するようにするには、source_langをautoに設定します。ソース言語を指定すると、翻訳の精度が向上します。
カスタムプロンプト を使用して言語を設定することもできます。
以下の例は、OpenAI 互換および DashScope Python SDK を使用して Qwen-MT を呼び出す方法を示しています。
# 依存関係をインポートし、クライアントを作成します...
completion = client.chat.completions.create(
model="qwen-mt-flash", # モデルを選択
# messages パラメーターには、ロールが user に設定されたメッセージを 1 つだけ含める必要があり、そのコンテンツは翻訳対象のテキストです。
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"}},
)
# 依存関係をインポートします...
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"
)
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-flash",
# messages パラメーターには、ロールが 'user' のメッセージを正確に 1 つ含める必要があり、そのコンテンツは翻訳対象のテキストです。
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"
}
},
)
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-flash",
# messages パラメーターには、ロールが "user" のメッセージを正確に 1 つ含める必要があり、そのコンテンツは翻訳対象のテキストです。
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 | 一般的な使用に推奨。ウェブサイトやアプリのコンテンツ、製品説明、日常のコミュニケーション、ブログ投稿に適しています | 良 | 高速 | 低 | 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: Bearer $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 と qwen-mt-lite のみです。
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 と qwen-mt-lite のみでサポートされています。
.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: Bearer $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フィールドに割り当てます。配列内の各オブジェクトは、ソース term を必須の翻訳にマップします:
{
"source": "term",
"target": "pre-translated term"
}
-
規約に同意
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 はリージョンによって異なります。ご利用のリージョンに基づいて更新してください。
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: Bearer $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: Bearer $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 句がない場合に 1 番目の SELECT 文が返す行数を返します。
==================================================
--- [ドメインありの翻訳結果] ---
2 番目の SELECT 文は、LIMIT 句を含めなかった場合に 1 番目の 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: Bearer $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 (target_lang、source_lang など) の設定がカスタムプロンプト内の対応する設定より優先され、カスタムプロンプト内の言語やスタイルの指定をオーバーライドします。
最適な翻訳結果を得るには、代わりに
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 = [{"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 = [
{
"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 |
Valaisan | 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」をご参照ください。