Qwen-MT is a large language model (LLM) for machine translation fine-tuned from Qwen3. It supports translation across 92 languages, including Chinese, English, Japanese, Korean, French, Spanish, German, Thai, Indonesian, Vietnamese, and Arabic. The model also provides features such as term intervention, domain prompting, and translation memory to enhance translation quality in complex application scenarios.
How it works
Provide the text to translate: The
messagesarray must contain a single message with itsroleset touser. Thecontentof this message is the text to be translated.Set languages: Set the source language (
source_lang) and target language (target_lang) in thetranslation_optionsparameter. For a list of supported languages, see Supported languages. To automatically detect the source language, setsource_langtoauto.Specifying the source language improves translation accuracy.
You can also set the language using custom prompts.
The following examples show how to call the Qwen-MT model using the OpenAI compatible and DashScope Python SDKs.
OpenAI compatible
# Import dependencies and create a client...
completion = client.chat.completions.create(
model="qwen-mt-flash", # Select the model
# The messages parameter must contain only one message with the role set to user, and its content is the text to be translated.
messages=[{"role": "user", "content": "No me reí después de ver este video"}],
# Because translation_options is not a standard OpenAI parameter, it must be passed in the extra_body parameter.
extra_body={"translation_options": {"source_lang": "auto", "target_lang": "English"}},
)DashScope
# Import dependencies...
response = dashscope.Generation.call(
api_key=os.getenv("DASHSCOPE_API_KEY"),
model="qwen-mt-flash", # Select a model
messages=[{"role": "user", "content": "No me reí después de ver este video"}], # messages: 'role' is 'user' and 'content' is the text to be translated.
translation_options={"source_lang": "auto", "target_lang": "English"}, # Configure translation options.
result_format="message"
)Limitations
Single-turn translation only: The model is designed for translation tasks and does not support multi-turn conversations.
System messages not supported: You cannot set global behavior using a message with the
systemrole. Instead, define translation configurations in thetranslation_optionsparameter.
Model selection
For general scenarios, you can select
qwen-mt-flash. It balances quality, speed, and cost, and supports incremental streaming output.For the highest translation quality in professional fields, you can select
qwen-mt-plus.For the fastest response speed in simple, real-time scenarios, you can select
qwen-mt-lite.
The following table compares the models.
Model | Recommended scenarios | Result | Speed | Cost | Supported languages | Supports incremental streaming output |
qwen-mt-plus | Scenarios that require high translation quality, such as professional fields, formal documents, academic papers, and technical reports | Best | Standard | High | 92 | No |
qwen-mt-flash | Top choice for general use. Suitable for scenarios such as website/app content, product descriptions, daily communication, and blog posts | Good | Fast | Low | 92 | Yes |
qwen-mt-turbo | Alternative option. The flash model offers better quality and features. Select the flash model. | Fair | Fast | Low | 92 | No |
qwen-mt-lite | Simple, latency-sensitive scenarios such as real-time chat and live comment translation | Basic | Fastest | Lowest | 31 | Yes |
For more information about model context and pricing, see Qwen-MT. For information about concurrent request limits, see Qwen-MT.
Getting started
This section shows a simple example of translating "No me reí después de ver este video" into English.
You must obtain an API key and set the API key as an environment variable. If you use the OpenAI SDK or DashScope SDK to make calls, you must also install the SDK.
OpenAI compatible
Sample request
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the Beijing region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English"
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-flash",
"messages": [{"role": "user", "content": "No me reí después de ver este video"}],
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}'
Sample response
I didn't laugh after watching this video. DashScope
Sample request
The DashScope Java SDK must be version 2.20.6 or later.
import os
import dashscope
# If you use a model in the China (Beijing) region, replace base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-turbo", # This example uses qwen-mt-turbo. You can replace it with another model name as needed.
messages=messages,
result_format='message',
translation_options=translation_options
)
print(response.output.choices[0].message.content)// DashScope SDK 2.20.6 or later is required.
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 {
// The following URL is for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("No me reí después de ver este video")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.build();
GenerationParam param = GenerationParam.builder()
// If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio 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("Error message: "+e.getMessage());
e.printStackTrace();
} finally {
System.exit(0);
}
}
}# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "No me reí después de ver este video",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}
}'Sample response
I didn't laugh after watching this video. Streaming output
Streaming output returns translated content in real time to reduce user wait times. Currently, only qwen-mt-flash and qwen-mt-lite support incremental streaming output, where each response contains only the newly generated content. You can enable this feature using the incremental_output parameter. The qwen-mt-plus and qwen-mt-turbo models support only non-incremental streaming output. Each response returns the entire sequence generated so far, and the final response contains the complete result. For more information, see Streaming output.
OpenAI compatible
Sample request
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "No me reí después de ver este video"}]
translation_options = {"source_lang": "auto", "target_lang": "English"}
completion = client.chat.completions.create(
model="qwen-mt-flash",
messages=messages,
stream=True,
stream_options={"include_usage": True},
extra_body={"translation_options": translation_options},
)
for chunk in completion:
if chunk.choices:
content = chunk.choices[0].delta.content or ""
print(content, end="", flush=True)
else:
print("="*20+"Usage"+"="*20)
print(chunk.usage)# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-flash",
"messages": [{"role": "user", "content": "No me reí después de ver este video"}],
"stream": true,
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}'Sample response
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
Sample request
import os
import dashscope
# If you use a model in the China (Beijing) region, replace base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-flash", # This example uses qwen-mt-turbo. You can replace it with another model name as needed.
messages=messages,
result_format='message',
stream=True,
# To get incremental output, set incremental_output to True. This is recommended. Currently, only qwen-mt-flash supports this feature.
incremental_output=True,
translation_options=translation_options
)
for chunk in response:
print(chunk.output.choices[0].message.content, end="", flush=True)// The DashScope SDK must be version 2.20.6 or later.
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)
// Enable incremental output. This is supported only by qwen-mt-flash.
.incrementalOutput(true)
.messages(Arrays.asList(userMsg))
.build();
}
public static void main(String[] args) {
try {
// The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("No me reí después de ver este video").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-mt-flash",
"input": {
"messages": [
{
"content": "No me reí después de ver este video",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
},
"incremental_output":true
}'Sample response
I didn't laugh after watching this video. The qwen-mt-plus and qwen-mt-turbo models do not currently support incremental streaming output.
Improve translation quality
Standard translation is sufficient for simple use cases, such as daily communication. However, for professional or demanding translation tasks, you may encounter the following issues:
Inconsistent terminology: Product names or industry terms are translated incorrectly.
Mismatched style: The style of the translated text does not meet the standards of specific domains, such as legal or marketing.
You can use term intervention, translation memory, and domain prompting to resolve these issues.
Term intervention
To ensure translation accuracy and consistency when text contains brand names, product names, or technical terms, you can provide a glossary in the terms field. This instructs the model to use your specified translations.
Define and pass terms as follows:
Define terms
Create a JSON array and assign it to the
termsfield. Each object in the array represents a term in the following format:{ "source": "term", "target": "pre-translated term" }Pass the terms
Use the
translation_optionsparameter to pass the definedtermsarray.
OpenAI compatible
Sample request
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
# --- First request: without the terms parameter ---
print("--- [Translation result without 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") # Separator for comparison
# --- Second request: with the terms parameter ---
print("--- [Translation result with 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)# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
}'Sample response
After you add the terms, the translation result is consistent with the terms you passed: "biological sensor" and "health status of the body".
--- [Translation result without 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.
==================================================
--- [Translation result with 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
Sample request
import os
import dashscope
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-turbo", # This example uses qwen-mt-turbo. You can replace it with another model name as needed.
messages=messages,
result_format='message',
translation_options=translation_options
)
print(response.output.choices[0].message.content)// The DashScope SDK must be version 2.20.6 or later.
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 {
// The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.")
.build();
Term term1 = Term.builder()
.source("biosensor")
.target("biological sensor")
.build();
Term term2 = Term.builder()
.source("estado de salud del cuerpo")
.target("health status of the body")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.terms(Arrays.asList(term1, term2))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
}'Sample response
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. Translation memory
To instruct the model to use a specific translation style or sentence pattern, you can provide source-target sentence pairs as examples in the tm_list field. The model then imitates the style of these examples for the current translation task.
Define the translation memory
Create a JSON array named
tm_list. Each JSON object in the array contains a source sentence and its corresponding translated sentence in the following format:{ "source": "source statement", "target": "translated statement" }Pass the translation memory
Use the
translation_optionsparameter to pass the translation memory array.
The following code shows how to use the translation memory feature.
OpenAI compatible
Sample request
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"tm_list":[
{"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
{"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
]
}
}'Sample response
You can run the following command to view the version of Thrift that is installed:DashScope
Sample request
import os
import dashscope
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]}
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-turbo", # This example uses qwen-mt-turbo. You can replace it with another model name as needed.
messages=messages,
result_format='message',
translation_options=translation_options
)
print(response.output.choices[0].message.content)// The DashScope SDK must be version 2.20.6 or later.
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 {
// The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("El siguiente comando muestra la información de la versión de Thrift instalada.")
.build();
Tm tm1 = Tm.builder()
.source("Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:")
.target("You can use one of the following methods to query the engine version of a cluster:")
.build();
Tm tm2 = Tm.builder()
.source("La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.")
.target("The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website.")
.build();
Tm tm3 = Tm.builder()
.source("Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:")
.target("You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.tmList(Arrays.asList(tm1, tm2, tm3))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "El siguiente comando muestra la información de la versión de Thrift instalada.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"tm_list":[
{"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
{"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
]
}
}'Sample response
You can use the following commands to check the version information of thrift installed; Domain prompting
To adapt the translation style to a specific domain, you can use the translation_options parameter to pass a domain prompt. For example, translations for legal or government domains should be formal, while those for social media should be colloquial.
Domain prompts currently support only English.
OpenAI compatible
Sample request
import os
from openai import OpenAI
client = OpenAI(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
# --- First request: without the domains parameter ---
print("--- [Translation result without 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") # Separator for comparison
# --- Second request: with the domains parameter ---
print("--- [Translation result with 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)# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
}'Sample response
--- [Translation result without domains] ---
The second SELECT statement returns a number indicating how many rows the first SELECT statement would return without the LIMIT clause.
==================================================
--- [Translation result with 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
Sample request
import os
import dashscope
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv('DASHSCOPE_API_KEY'),
model="qwen-mt-turbo", # This example uses qwen-mt-turbo. You can replace it with another model name as needed.
messages=messages,
result_format='message',
translation_options=translation_options
)
print(response.output.choices[0].message.content)// The DashScope SDK must be version 2.20.6 or later.
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 {
// The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.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);
}
}# ======= Important =======
# If you use a model in the China (Beijing) region, replace the URL with: https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === Delete this comment before execution ====
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
}
}'Sample response
The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause. Custom prompts
For the best translation results, use the translation_options parameter to configure translation settings. However, Qwen-MT also supports using prompts to specify translation requirements, such as language and style, without using the translation_options parameter.
The following example shows a Spanish-to-English translation in the legal domain:
OpenAI compatible
import os
from openai import OpenAI
client = OpenAI(
# If the environment variable is not configured, replace the following line with your Alibaba Cloud Model Studio API Key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# If you use a model in the China (Beijing) region, you need to replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
prompt_template = """
# Role
You are a professional legal translation expert, proficient in both Spanish and English, and you are especially skilled at handling commercial contracts and legal documents.
# Task
I need you to translate the following Spanish legal text into professional, accurate, and formal English.
# Translation Requirements
1. **Fidelity to the Original**: Strictly translate according to the meaning and legal intent of the original text. Do not add or omit information.
2. **Precise Terminology**: Use standard legal terms common in the Common Law system. For example, "甲方" should be translated as "Party A", "乙方" as "Party B", and "不可抗力" as "Force Majeure".
3. **Formal Tone**: Maintain the rigorous, objective, and formal style inherent in legal documents.
4. **Clarity of Language**: The translation must be clear, unambiguous, and conform to the expressive conventions of English legal writing.
5. **Format Preservation**: Retain the paragraphs, numbering, and basic format of the original text.
# Text to be Translated
{text_to_translate}
"""
# --- 2. Prepare the legal text to be translated ---
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. Construct the messages ---
messages = [{"role": "user", "content": final_prompt}]
# --- 4. Initiate the API request ---
completion = client.chat.completions.create(model="qwen-mt-plus", messages=messages)
# --- 5. Print the model's translation result ---
translation_result = completion.choices[0].message.content
print(translation_result)import OpenAI from 'openai';
const client = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
// If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/compatible-mode/v1
baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
});
const promptTemplate = `
# Role
You are a professional legal translation expert, proficient in both Spanish and English, specializing in business contracts and legal documents.
# Task
I need you to translate the following Spanish legal text into professional, accurate, and formal English.
# Translation Requirements
1. **Fidelity to the Original**: Translate strictly according to the meaning and legal intent of the original text. Do not add or omit information.
2. **Precise Terminology**: Use standard legal terms common in the Common Law system. For example, "甲方" should be translated as "Party A", "乙方" as "Party B", and "不可抗力" as "Force Majeure".
3. **Formal Tone**: Maintain the rigorous, objective, and formal tone inherent in legal documents.
4. **Clarity**: The translation must be clear, unambiguous, and conform to the expressive conventions of English legal writing.
5. **Format Preservation**: Retain the paragraphs, numbering, and basic format of the original text.
# Text to Translate
{text_to_translate}
`;
const spanishLegalText = "This Contract shall become effective from the date of signature and seal by both parties and shall be valid for a period of one year.";
const finalPrompt = promptTemplate.replace('{text_to_translate}', spanishLegalText);
const messages = [{"role": "user", "content": finalPrompt}];
async function main() {
const completion = await client.chat.completions.create({
model: "qwen-mt-plus",
messages: messages
});
const translationResult = completion.choices[0].message.content;
console.log(translationResult);
}
main();Sample response
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
Sample request
import os
import dashscope
# If you use a model in the China (Beijing) region, replace the base_url with: https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
prompt_template = """
# Role
You are a professional legal translation expert, proficient in both Spanish and English, with special expertise in handling business contracts and legal documents.
# Task
I need you to translate the following Spanish legal text into professional, accurate, and formal English.
# Translation Requirements
1. **Fidelity to the Original**: Strictly translate according to the meaning and legal intent of the original text. Do not add or omit any information.
2. **Precise Terminology**: Use standard legal terms common to the Common Law system. For example, "甲方" should be translated as "Party A", "乙方" as "Party B", and "不可抗力" as "Force Majeure".
3. **Formal Tone**: Maintain the rigorous, objective, and formal style inherent in legal documents.
4. **Clear Phrasing**: The translation must be clear, unambiguous, and conform to the conventions of English legal writing.
5. **Preserve Formatting**: Maintain the paragraphs, numbering, and basic format of the original text.
# Text to be Translated
{text_to_translate}
"""
# --- 2. Prepare the legal text for translation ---
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. Construct the messages ---
messages = [
{
"role": "user",
"content": final_prompt
}
]
response = dashscope.Generation.call(
# If you have not configured an environment variable, replace the following line with your Model Studio 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)// The DashScope SDK must be version 2.20.6 or later.
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 {
// The following is the URL for the Singapore region. If you use a model in the Beijing region, replace the URL with: https://dashscope.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
String promptTemplate = "# Role\n" +
"You are a professional legal translation expert, proficient in both Spanish and English, specializing in business contracts and legal documents.\n\n" +
"# Task\n" +
"I need you to translate the following Spanish legal text into professional, accurate, and formal English.\n\n" +
"# Translation Requirements\n" +
"1. **Fidelity to the Original**: Translate strictly according to the meaning and legal intent of the original text. Do not add or omit information.\n" +
"2. **Precise Terminology**: Use standard legal terms common in the Common Law system. For example, \"甲方\" should be translated as \"Party A\", \"乙方\" as \"Party B\", and \"不可抗力\" as \"Force Majeure\".\n" +
"3. **Formal Tone**: Maintain the rigorous, objective, and formal tone inherent in legal documents.\n" +
"4. **Clarity**: The translation must be clear, unambiguous, and conform to the expressive conventions of English legal writing.\n" +
"5. **Format Preservation**: Retain the paragraphs, numbering, and basic format of the original text.\n\n" +
"# Text to Translate\n" +
"{text_to_translate}";
String spanishLegalText = "This Contract shall become effective from the date of signature and seal by both parties and shall be valid for a period of one year.";
String finalPrompt = promptTemplate.replace("{text_to_translate}", spanishLegalText);
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content(finalPrompt)
.build();
GenerationParam param = GenerationParam.builder()
// If you have not configured an environment variable, replace the following line with your Model Studio 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("Error message: "+e.getMessage());
e.printStackTrace();
}
}
}Sample response
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.Going live
Control the input token count
The Qwen-MT models have a maximum input limit of 8,192 tokens. For long content, consider the following strategies to control the number of input tokens:
Translate in segments: When you translate long text, process it in segments. Split the text based on semantic units, such as paragraphs or complete sentences, instead of by character count. This approach preserves contextual integrity and improves translation quality.
Provide the most relevant reference content: Terms, translation memory, and domain prompts are added to the input prompt as tokens. To optimize token usage, provide only the reference content that is most relevant to the current task. Avoid using large, generic lists.
Set
source_langbased on the scenarioWhen the source language is uncertain, such as in social chat scenarios with multilingual text, set
source_langtoauto. The model automatically identifies the source language.In scenarios with a fixed language and high accuracy requirements, such as for technical documents or operation manuals, always specify
source_lang. Explicitly defining the source language improves translation accuracy.
Supported languages
Use the English name or Code from the table below when you send a request.
If you are unsure of the source language, you can set thesource_langparameter toautofor automatic detection.
Languages supported by qwen-mt-plus/flash/turbo (92)
Language | English name | Code |
English | English | en |
Simplified Chinese | Chinese | zh |
Traditional Chinese | Traditional Chinese | zh_tw |
Russian | Russian | ru |
Japanese | Japanese | ja |
Korean | Korean | ko |
Spanish | Spanish | es |
French | French | fr |
Portuguese | Portuguese | pt |
German | German | de |
Italian | Italian | it |
Thai | Thai | th |
Vietnamese | Vietnamese | vi |
Indonesian | Indonesian | id |
Malay | Malay | ms |
Arabic | Arabic | ar |
Hindi | Hindi | hi |
Hebrew | Hebrew | he |
Burmese | Burmese | my |
Tamil | Tamil | ta |
Urdu | Urdu | ur |
Bengali | Bengali | bn |
Polish | Polish | pl |
Dutch | Dutch | nl |
Romanian | Romanian | ro |
Turkish | Turkish | tr |
Khmer | Khmer | km |
Lao | Lao | lo |
Cantonese | Cantonese | yue |
Czech | Czech | cs |
Greek | Greek | el |
Swedish | Swedish | sv |
Hungarian | Hungarian | hu |
Danish | Danish | da |
Finnish | Finnish | fi |
Ukrainian | Ukrainian | uk |
Bulgarian | Bulgarian | bg |
Serbian | Serbian | sr |
Telugu | Telugu | te |
Afrikaans | Afrikaans | af |
Armenian | Armenian | hy |
Assamese | Assamese | as |
Asturian | Asturian | ast |
Basque | Basque | eu |
Belarusian | Belarusian | be |
Bosnian | Bosnian | bs |
Catalan | Catalan | ca |
Cebuano | Cebuano | ceb |
Croatian | Croatian | hr |
Egyptian Arabic | Egyptian Arabic | arz |
Estonian | Estonian | et |
Galician | Galician | gl |
Georgian | Georgian | ka |
Gujarati | Gujarati | gu |
Icelandic | Icelandic | is |
Javanese | Javanese | jv |
Kannada | Kannada | kn |
Kazakh | Kazakh | kk |
Latvian | Latvian | lv |
Lithuanian | Lithuanian | lt |
Luxembourgish | Luxembourgish | lb |
Macedonian | Macedonian | mk |
Maithili | Maithili | mai |
Maltese | Maltese | mt |
Marathi | Marathi | mr |
Mesopotamian Arabic | Mesopotamian Arabic | acm |
Moroccan Arabic | Moroccan Arabic | ary |
Najdi Arabic | Najdi Arabic | ars |
Nepali | Nepali | ne |
North Azerbaijani | North Azerbaijani | az |
North Levantine Arabic | North Levantine Arabic | apc |
Northern Uzbek | Northern Uzbek | uz |
Norwegian Bokmål | Norwegian Bokmål | nb |
Norwegian Nynorsk | Norwegian Nynorsk | nn |
Occitan | Occitan | oc |
Odia | Odia | or |
Pangasinan | Pangasinan | pag |
Sicilian | Sicilian | scn |
Sindhi | Sindhi | sd |
Sinhala | Sinhala | si |
Slovak | Slovak | sk |
Slovenian | Slovenian | sl |
South Levantine Arabic | South Levantine Arabic | ajp |
Swahili | Swahili | sw |
Tagalog | Tagalog | tl |
Ta’izzi-Adeni Arabic | Ta’izzi-Adeni Arabic | acq |
Tosk Albanian | Tosk Albanian | sq |
Tunisian Arabic | Tunisian Arabic | aeb |
Venetian | Venetian | vec |
Valaisan | Waray | war |
Welsh | Welsh | cy |
Western Persian | Western Persian | fa |
Languages supported by qwen-mt-lite (31)
Language | English name | Code |
English | English | en |
Simplified Chinese | Chinese | zh |
Traditional Chinese | Traditional Chinese | zh_tw |
Russian | Russian | ru |
Japanese | Japanese | ja |
Korean | Korean | ko |
Spanish | Spanish | es |
French | French | fr |
Portuguese | Portuguese | pt |
German | German | de |
Italian | Italian | it |
Thai | Thai | th |
Vietnamese | Vietnamese | vi |
Indonesian | Indonesian | id |
Malay | Malay | ms |
Arabic | Arabic | ar |
Hindi | Hindi | hi |
Hebrew | Hebrew | he |
Urdu | Urdu | ur |
Bengali | Bengali | bn |
Polish | Polish | pl |
Dutch | Dutch | nl |
Turkish | Turkish | tr |
Khmer | Khmer | km |
Czech | Czech | cs |
Swedish | Swedish | sv |
Hungarian | Hungarian | hu |
Danish | Danish | da |
Finnish | Finnish | fi |
Tagalog | Tagalog | tl |
Persian | Persian | fa |
API reference
For the input and output parameters of Qwen-MT, see Qwen-MT translation model.