翻譯能力(Qwen-MT)
Qwen-MT模型是基於Qwen3模型最佳化的機器翻譯大語言模型,支援92個語種(包括中、英、日、韓、法、西、德、泰、印尼、越、阿等)互譯,且提供了術語幹預、領域提示、記憶庫等能力,提升模型在複雜應用情境下的翻譯效果。
工作方式
傳入待翻譯內容:
messages數組中有且僅有一個role為user的訊息,其content為待翻譯文本。設定語種:參考支援的語言,在
translation_options中設定源語種 (source_lang) 和目標語種 (target_lang)。若需自動檢測源語種,可將source_lang設為auto。指明源語種有利於提升翻譯準確率。
Qwen-MT 模型也支援通過 自訂提示詞 設定語種。
以下以 OpenAI 相容和 DashScope 的 Python SDK為例,示範 Qwen-MT 的基本調用方式。所有翻譯配置均通過 translation_options 參數傳入。
OpenAI 相容
# 匯入依賴與建立用戶端...
completion = client.chat.completions.create(
model="qwen-mt-flash", # 選擇模型
# messages 有且僅有一個 role 為 user 的訊息,其 content 為待翻譯文本
messages=[{"role": "user", "content": "我看到這個視頻後沒有笑"}],
# 由於 translation_options 非 OpenAI 標準參數,需要通過 extra_body 傳入
extra_body={"translation_options": {"source_lang": "Chinese", "target_lang": "English"}},
)DashScope
# 匯入依賴...
response = dashscope.Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-mt-flash", # 選擇模型
messages=[{"role": "user", "content": "我看到這個視頻後沒有笑"}], # messages: role為user, content為待翻譯文本
translation_options={"source_lang": "Chinese", "target_lang": "English"}, # 配置翻譯選項
result_format="message"
)OpenAI 相容
import os
from openai import OpenAI
client = OpenAI(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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 的訊息,其 content 為待翻譯文本
messages=[
{
"role": "user",
"content": "我看到這個視頻後沒有笑"
}
],
# 由於 translation_options 非 OpenAI 標準參數,需要通過 extra_body 傳入
extra_body={
# 配置翻譯選項
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English"
}
},
)DashScope
import os
import dashscope
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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 的訊息,其 content 為待翻譯文本
messages=[
{
"role": "user",
"content": "我看到這個視頻後沒有笑"
}
],
# 配置翻譯選項
translation_options={
"source_lang": "auto",
"target_lang": "English",
},
result_format="message"
)
print(response.output.choices[0].message.content)使用限制:
僅支援單輪翻譯:模型專為翻譯任務設計,不支援多輪對話。
不支援設定 System Message:不支援通過
system角色的訊息來設定全域行為。翻譯配置通過translation_options中定義。
模型選型
通用情境首選
qwen-mt-flash,在翻譯品質、速度和成本之間取得最佳平衡,支援增量流式輸出。最高翻譯品質(專業文獻、正式文書)選
qwen-mt-plus。最低延遲(即時聊天等簡單情境)選
qwen-mt-lite。
各模型詳細對比如下:
模型 | 推薦情境 | 效果 | 速度 | 成本 | 支援的語言 | 支援增量流式輸出 |
qwen-mt-plus | 專業領域、正式文書、論文、技術報告等對譯文品質要求高的情境 | 最好 | 標準 | 較高 | 92種 | |
qwen-mt-flash | 通用首選,適用於網站/App內容、商品描述、日常溝通、部落格文章等情境 | 較好 | 較快 | 較低 | 92種 | |
qwen-mt-turbo | turbo模型後續不再更新,建議選用效果與功能均更優的flash模型 | 良好 | 較快 | 較低 | 92種 | |
qwen-mt-lite | 即時聊天、彈幕翻譯等對延遲敏感的簡單情境 | 基礎 | 最快 | 最低 | 31種 |
快速開始
以下樣本將 “我看到這個視頻後沒有笑” 翻譯為英文。
您需要已擷取API Key並配置API Key到環境變數。如果通過OpenAI SDK或DashScope SDK進行調用,還需要安裝SDK。請將範例程式碼中的 DASHSCOPE_API_HOST 替換為擷取的 API Host。
OpenAI相容
請求樣本
import os
from openai import OpenAI
client = OpenAI(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "我看到這個視頻後沒有笑"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English"
}
completion = client.chat.completions.create(
model="qwen-mt-flash", # 此處以 qwen-mt-flash 為例,可按需更換模型名稱
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= 重要提示 =======
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "我看到這個視頻後沒有笑"}],
"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
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "我看到這個視頻後沒有笑"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為: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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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("我看到這個視頻後沒有笑")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.build();
GenerationParam param = GenerationParam.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.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("錯誤資訊:"+e.getMessage());
e.printStackTrace();
} finally {
System.exit(0);
}
}
}# ======= 重要提示 =======
# 以下為華北2(北京)地區的URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
# === 執行時請刪除該注釋 ====
curl -X POST https://{WorkspaceId}.cn-beijing.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": "我看到這個視頻後沒有笑",
"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(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "我看到這個視頻後沒有笑"}]
translation_options = {"source_lang": "Chinese", "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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "我看到這個視頻後沒有笑"}],
"stream": true,
"translation_options": {
"source_lang": "Chinese",
"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
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "我看到這個視頻後沒有笑"
}
]
translation_options = {
"source_lang": "Chinese",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-flash", # 此處以qwen-mt-flash為例,可按需更換模型名稱
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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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("我看到這個視頻後沒有笑").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}# ======= 重要提示 =======
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "我看到這個視頻後沒有笑",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English"
},
"incremental_output":true
}'響應樣本
I didn't laugh after watching this video. qwen-mt-plus、qwen-mt-turbo模型不支援增量式流式輸出。
提升翻譯效果
標準翻譯能滿足日常溝通需求,但在專業情境中可能出現以下問題:
術語不統一:產品名或行業術語翻譯錯誤。
風格不匹配:譯文風格不符合法律、營銷等特定領域的規範。
以下三種方式可針對性地解決這些問題:
術語幹預
當文本包含品牌名、產品名或專業術語時,為保證翻譯的準確性和一致性,可通過 terms 欄位提供一個術語表,引導模型參考術語表進行翻譯。
使用步驟:
定義術語
建立JSON數組,賦值給
terms欄位。每個對象代表一條術語:{ "source": "術語", "target": "提前翻譯好的術語" }傳入術語
通過
translation_options參數傳入terms數組。
OpenAI相容
請求樣本
import os
from openai import OpenAI
client = OpenAI(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
}
]
# --- 第一次請求:不使用 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") # 用於分割,方便對比
# --- 第二次請求:使用 terms 參數 ---
print("--- [使用 terms] 的翻譯結果 ---")
translation_options_with_terms = {
"source_lang": "Chinese",
"target_lang": "English",
"terms": [
{
"source": "生物特徵辨識感應器",
"target": "biological sensor"
},
{
"source": "身體健康情況",
"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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
}
],
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English",
"terms": [
{
"source": "生物特徵辨識感應器",
"target": "biological sensor"
},
{
"source": "身體健康情況",
"target": "health status of the body"
}
]
}
}'響應樣本
加入術語後,翻譯結果與傳入的術語一致:“生物特徵辨識感應器”(biological sensor)和“身體健康情況”(the health status of the body)。
--- [不使用 terms] 的翻譯結果 ---
This set of biosensors uses graphene, a new material, whose target substance is chemical elements. Its sensitive "sense of smell" allows it to more deeply and accurately reflect one's health condition.
==================================================
--- [使用 terms] 的翻譯結果 ---
This biological sensor uses a new material called graphene. Its target is chemical elements, and its sensitive "sense of smell" enables it to reflect the health status of the body more deeply and accurately.DashScope
請求樣本
import os
import dashscope
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
}
]
translation_options = {
"source_lang": "Chinese",
"target_lang": "English",
"terms": [
{
"source": "生物特徵辨識感應器",
"target": "biological sensor"
},
{
"source": "身體健康情況",
"target": "health status of the body"
}
]
}
response = dashscope.Generation.call(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為: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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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("而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。")
.build();
Term term1 = Term.builder()
.source("生物特徵辨識感應器")
.target("biological sensor")
.build();
Term term2 = Term.builder()
.source("身體健康情況")
.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("錯誤資訊:"+e.getMessage());
}
System.exit(0);
}
}# ======= 重要提示 =======
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English",
"terms": [
{
"source": "生物特徵辨識感應器",
"target": "biological sensor"
},
{
"source": "身體健康情況",
"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 欄位提供"源文-譯文"句對作為參考。模型將在當次翻譯任務中模仿這些樣本的風格,適合維護大型文檔集的術語一致性,或沿用企業已有的寫作規範。
定義翻譯記憶
建立JSON數組賦值給
tm_list,每個對象包含源語句與對應譯文:{ "source": "源語句", "target": "已翻譯的語句" }傳入翻譯記憶
通過
translation_options參數傳入翻譯記憶數組。
可參考以下代碼實現翻譯記憶功能。
OpenAI相容
請求樣本
import os
from openai import OpenAI
client = OpenAI(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "通過如下命令可以看出安裝thrift的版本資訊;"
}
]
translation_options = {
"source_lang": "Chinese",
"target_lang": "English",
"tm_list": [
{
"source": "您可以通過如下方式查看叢集的核心版本資訊:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考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": "您可以通過PyPI來安裝SDK,安裝命令如下:",
"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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "通過如下命令可以看出安裝thrift的版本資訊;"
}
],
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English",
"tm_list":[
{"source": "您可以通過如下方式查看叢集的核心版本資訊:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考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": "您可以通過PyPI來安裝SDK,安裝命令如下:", "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
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "通過如下命令可以看出安裝thrift的版本資訊;"
}
]
translation_options = {
"source_lang": "Chinese",
"target_lang": "English",
"tm_list": [
{
"source": "您可以通過如下方式查看叢集的核心版本資訊:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考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": "您可以通過PyPI來安裝SDK,安裝命令如下:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]}
response = dashscope.Generation.call(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為: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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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("通過如下命令可以看出安裝thrift的版本資訊;")
.build();
Tm tm1 = Tm.builder()
.source("您可以通過如下方式查看叢集的核心版本資訊:")
.target("You can use one of the following methods to query the engine version of a cluster:")
.build();
Tm tm2 = Tm.builder()
.source("我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考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("您可以通過PyPI來安裝SDK,安裝命令如下:")
.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("錯誤資訊:"+e.getMessage());
}
System.exit(0);
}
}# ======= 重要提示 =======
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "通過如下命令可以看出安裝thrift的版本資訊;",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "Chinese",
"target_lang": "English",
"tm_list":[
{"source": "您可以通過如下方式查看叢集的核心版本資訊:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考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": "您可以通過PyPI來安裝SDK,安裝命令如下:", "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(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
}
]
# --- 第一次請求:不使用 domains 參數 ---
print("--- [不使用 domains] 的翻譯結果 ---")
translation_options_without_domains = {
"source_lang": "Chinese",
"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") # 用於分割,方便對比
# --- 第二次請求:使用 domains 參數 (您的原始代碼) ---
print("--- [使用 domains] 的翻譯結果 ---")
translation_options_with_domains = {
"source_lang": "Chinese",
"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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
}
],
"translation_options": {
"source_lang": "Chinese",
"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."
}
}'響應樣本
--- [不使用 domains] 的翻譯結果 ---
The second SELECT statement returns a number indicating how many rows the first SELECT statement would return without the LIMIT clause.
==================================================
--- [使用 domains] 的翻譯結果 ---
The second SELECT statement returns a number that indicates how many rows the first SELECT statement would have returned if it had not included a LIMIT clause.DashScope
請求樣本
import os
import dashscope
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
}
]
translation_options = {
"source_lang": "Chinese",
"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(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為: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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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("第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("錯誤資訊:"+e.getMessage());
}
System.exit(0);
}
}# ======= 重要提示 =======
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "Chinese",
"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(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
prompt_template = """
# 角色
你是一名專業的法律翻譯專家,精通中文和英文,尤其擅長處理商業合約和法律檔案。
# 任務
我需要你將以下中文法律文本翻譯成專業、精準、正式的英文。
# 翻譯要求
1. **忠實原文**:嚴格按照原文的含義和法律意圖進行翻譯,不得添加或刪減資訊。
2. **術語精準**:使用英美法系(Common law)通用的標準法律術語。例如,“甲方”應翻譯為 "Party A",“乙方”應翻譯為 "Party B",“不可抗力”應翻譯為 "Force Majeure"。
3. **語氣正式**:保持法律檔案固有的嚴謹、客觀和正式的語體。
4. **語句清晰**:譯文必須清晰、無歧義,符合英文法律文書的表達習慣。
5. **格式保留**:保持原文的段落、編號和基本格式。
# 待翻譯文本
{text_to_translate}
"""
# --- 2. 準備待翻譯的法律文本 ---
chinese_legal_text = "本合約自雙方簽字蓋章之日起生效,有效期間為一年。"
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,
// 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});
const promptTemplate = `
# 角色
你是一名專業的法律翻譯專家,精通中文和英文,尤其擅長處理商業合約和法律檔案。
# 任務
我需要你將以下中文法律文本翻譯成專業、精準、正式的英文。
# 翻譯要求
1. **忠實原文**:嚴格按照原文的含義和法律意圖進行翻譯,不得添加或刪減資訊。
2. **術語精準**:使用英美法系(Common law)通用的標準法律術語。例如,“甲方”應翻譯為 "Party A",“乙方”應翻譯為 "Party B",“不可抗力”應翻譯為 "Force Majeure"。
3. **語氣正式**:保持法律檔案固有的嚴謹、客觀和正式的語體。
4. **語句清晰**:譯文必須清晰、無歧義,符合英文法律文書的表達習慣。
5. **格式保留**:保持原文的段落、編號和基本格式。
# 待翻譯文本
{text_to_translate}
`;
const chineseLegalText = "本合約自雙方簽字蓋章之日起生效,有效期間為一年。";
const finalPrompt = promptTemplate.replace('{text_to_translate}', chineseLegalText);
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
# 以下為新加坡地區URL,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的URL不同。
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
prompt_template = """
# 角色
你是一名專業的法律翻譯專家,精通中文和英文,尤其擅長處理商業合約和法律檔案。
# 任務
我需要你將以下中文法律文本翻譯成專業、精準、正式的英文。
# 翻譯要求
1. **忠實原文**:嚴格按照原文的含義和法律意圖進行翻譯,不得添加或刪減資訊。
2. **術語精準**:使用英美法系(Common law)通用的標準法律術語。例如,“甲方”應翻譯為 "Party A",“乙方”應翻譯為 "Party B",“不可抗力”應翻譯為 "Force Majeure"。
3. **語氣正式**:保持法律檔案固有的嚴謹、客觀和正式的語體。
4. **語句清晰**:譯文必須清晰、無歧義,符合英文法律文書的表達習慣。
5. **格式保留**:保持原文的段落、編號和基本格式。
# 待翻譯文本
{text_to_translate}
"""
# --- 2. 準備待翻譯的法律文本 ---
chinese_legal_text = "本合約自雙方簽字蓋章之日起生效,有效期間為一年。"
final_prompt = prompt_template.format(text_to_translate=chinese_legal_text)
# --- 3. 構建messages ---
messages = [
{
"role": "user",
"content": final_prompt
}
]
response = dashscope.Generation.call(
# 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為: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,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的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. **術語精準**:使用英美法系(Common law)通用的標準法律術語。例如,“甲方”應翻譯為 \"Party A\",“乙方”應翻譯為 \"Party B\",“不可抗力”應翻譯為 \"Force Majeure\"。\n" +
"3. **語氣正式**:保持法律檔案固有的嚴謹、客觀和正式的語體。\n" +
"4. **語句清晰**:譯文必須清晰、無歧義,符合英文法律文書的表達習慣。\n" +
"5. **格式保留**:保持原文的段落、編號和基本格式。\n\n" +
"# 待翻譯文本\n" +
"{text_to_translate}";
String chineseLegalText = "本合約自雙方簽字蓋章之日起生效,有效期間為一年。";
String finalPrompt = promptTemplate.replace("{text_to_translate}", chineseLegalText);
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content(finalPrompt)
.build();
GenerationParam param = GenerationParam.builder()
// 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.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("錯誤資訊:"+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.應用於生產環境
控制輸入 Token 數量
Qwen-MT 模型的輸入 Token 上限為 8,192。輸入內容較長時,可參考以下策略:
分段翻譯:按語義邊界(段落或完整句子)分割長文本,而非按字元數截斷,以保證上下文完整性,提升翻譯品質。
僅傳入最相關的參考內容:術語、翻譯記憶和領域提示都會作為輸入 Token 拼入提示詞。只傳入與當前翻譯任務直接相關的內容,避免使用大而泛的參考列表。
根據情境設定
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 模型的輸入與輸出參數請參考Qwen-MT 翻譯模型。