Qwen-MT is a machine translation model fine-tuned from Qwen3. It supports 92 languages -- including Chinese, English, Japanese, Korean, French, Spanish, German, Thai, Indonesian, Vietnamese, and Arabic -- and offers term intervention, domain prompting, and translation memory to control translation quality.
How it works
-
Provide the text to translate: The
messagesarray must contain a single message with itsroleset touser. Thecontentof this message is the text you want to translate. -
Set languages: Specify the source language (
source_lang) and target language (target_lang) in thetranslation_optionsparameter. For a list of supported languages, see Supported languages. To let the model detect the source language automatically, 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 Qwen-MT 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"
)
OpenAI compatible
import os
from openai import OpenAI
client = OpenAI(
# If the environment variable is not configured, replace the following line with your Model Studio API key: api_key="sk-xxx",
api_key=os.getenv("DASHSCOPE_API_KEY"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen-mt-turbo",
# The messages parameter must contain exactly one message with the role '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, you must pass it using the extra_body parameter.
extra_body={
# Configure translation options.
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
},
)
DashScope
import os
import dashscope
# The base_url varies by region. Update it based on the region you use.
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",
# The messages parameter must contain exactly one message with the role "user", and its content is the text to be translated.
messages=[
{
"role": "user",
"content": "No me reí después de ver este video"
}
],
# Configure translation options.
translation_options={
"source_lang": "auto",
"target_lang": "English",
}
result_format="message"
)
print(response.output.choices[0].message.content)
Use the translation_options parameter to access advanced translation features such as term intervention, translation memory, and domain prompting.
Limitations
-
Single-turn translation only: Qwen-MT is purpose-built for translation and does not support multi-turn conversations.
-
System messages not supported: You cannot set global behavior through a
system-role message. Instead, configure translation behavior in thetranslation_optionsparameter.
Model selection
-
For general scenarios, choose
qwen-mt-flash. It offers the best balance of quality, speed, and cost, and supports incremental streaming output. -
For the highest translation quality in professional domains, choose
qwen-mt-plus. -
For the fastest response speed in simple, real-time scenarios, choose
qwen-mt-lite.
The following table compares the available models.
|
Model |
Scenario |
Result |
Speed |
Cost |
Supported languages |
Incremental stream |
|
qwen-mt-plus |
Provides high-quality translation for scenarios such as professional fields, formal documents, academic papers, and technical reports |
Best |
Standard |
High |
92 |
|
|
qwen-mt-flash |
Recommended for general use. Suitable for website and app content, product descriptions, daily communication, and blog posts |
Good |
Fast |
Low |
92 |
|
|
qwen-mt-turbo |
This model will not be updated in the future. Use flash instead. |
Fair |
Fast |
Low |
92 |
|
|
qwen-mt-lite |
Simple, latency-sensitive scenarios like real-time chat and live comment translation |
Basic |
Fastest |
Lowest |
31 |
|
Check context window limits and pricing in the console. For concurrent request limits, see Qwen translation model.
Getting started
This section walks through a simple example: translating "No me reí después de ver este video" into English.
Obtain an API key and export the API key as an environment variable. If you use the OpenAI SDK or DashScope SDK to make calls, 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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English"
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-flash",
"messages": [{"role": "user", "content": "No me reí después de ver este video"}],
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}'
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
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("No me reí después de ver este video")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.build();
GenerationParam param = GenerationParam.builder()
// 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 =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "No me reí después de ver este video",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}
}'Sample response
I didn't laugh after watching this video.
Streaming output
Streaming output delivers translated content incrementally, reducing perceived latency. Currently, qwen-mt-flash and qwen-mt-lite support incremental streaming, where each response contains only the newly generated content. Enable it with the incremental_output parameter. qwen-mt-plus and qwen-mt-turbo support only non-incremental streaming, where each response returns the full translation so far. 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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "No me reí después de ver este video"}]
translation_options = {"source_lang": "auto", "target_lang": "English"}
completion = client.chat.completions.create(
model="qwen-mt-flash",
messages=messages,
stream=True,
stream_options={"include_usage": True},
extra_body={"translation_options": translation_options},
)
for chunk in completion:
if chunk.choices:
content = chunk.choices[0].delta.content or ""
print(content, end="", flush=True)
else:
print("="*20+"Usage"+"="*20)
print(chunk.usage)# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-flash",
"messages": [{"role": "user", "content": "No me reí después de ver este video"}],
"stream": true,
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
}
}'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
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "No me reí después de ver este video"
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
}
response = dashscope.Generation.call(
# 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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("No me reí después de ver este video").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-mt-flash",
"input": {
"messages": [
{
"content": "No me reí después de ver este video",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
},
"incremental_output":true
}'Sample response
I didn't laugh after watching this video.
qwen-mt-plus and qwen-mt-turbo do not support incremental streaming output.
Improve translation quality
Basic translation works well for everyday use cases like casual communication. For professional or high-stakes translation tasks, you may run into specific challenges:
-
Inconsistent terminology: Product names or industry-specific terms are translated incorrectly or inconsistently across passages.
-
Mismatched style: The translated text does not match the tone or conventions expected in a specific domain, such as legal or marketing content.
Qwen-MT provides three features to address these challenges: term intervention, translation memory, and domain prompting.
Term intervention
Supply a glossary in the terms field to ensure that brand names, product names, or technical terms are translated consistently every time.
To define and pass your glossary:
-
Define terms
Create a JSON array and assign it to the
termsfield. Each object in the array maps a source term to its required translation:{ "source": "term", "target": "pre-translated term" } -
Pass the terms
Pass the
translation_optionsparameter with yourtermsarray included.
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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
# --- 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 =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
}'Sample response
After you add the glossary, the translation output reflects your specified terms: "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
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
response = dashscope.Generation.call(
# 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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.")
.build();
Term term1 = Term.builder()
.source("biosensor")
.target("biological sensor")
.build();
Term term2 = Term.builder()
.source("estado de salud del cuerpo")
.target("health status of the body")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.terms(Arrays.asList(term1, term2))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"terms": [
{
"source": "biosensor",
"target": "biological sensor"
},
{
"source": "estado de salud del cuerpo",
"target": "health status of the body"
}
]
}
}
}'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
When you need the model to follow a specific translation style or sentence pattern, provide source-target sentence pairs as examples in the tm_list field. The model learns from the style of these reference pairs and applies it to the current translation. This is useful for maintaining consistency across large documentation sets or when adapting to an organization’s established writing conventions.
-
Define the translation memory
Create a JSON array named
tm_list. Each object pairs a source sentence with its reference translation:{ "source": "source statement", "target": "translated statement" } -
Pass the translation memory
Include the
translation_optionsparameter with your translation memory array.
The following example demonstrates translation memory in action.
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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]
}
completion = client.chat.completions.create(
model="qwen-mt-plus",
messages=messages,
extra_body={
"translation_options": translation_options
}
)
print(completion.choices[0].message.content)# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"tm_list":[
{"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
{"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
]
}
}'Sample response
You can run the following command to view the version of Thrift that is installed:
DashScope
Sample request
import os
import dashscope
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "El siguiente comando muestra la información de la versión de Thrift instalada."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"tm_list": [
{
"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:",
"target": "You can use one of the following methods to query the engine version of a cluster:"
},
{
"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.",
"target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
},
{
"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:",
"target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
}
]}
response = dashscope.Generation.call(
# 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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("El siguiente comando muestra la información de la versión de Thrift instalada.")
.build();
Tm tm1 = Tm.builder()
.source("Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:")
.target("You can use one of the following methods to query the engine version of a cluster:")
.build();
Tm tm2 = Tm.builder()
.source("La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.")
.target("The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website.")
.build();
Tm tm3 = Tm.builder()
.source("Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:")
.target("You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.tmList(Arrays.asList(tm1, tm2, tm3))
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-plus")
.messages(Collections.singletonList(userMsg))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
.build();
return gen.call(param);
}
public static void main(String[] args) {
try {
GenerationResult result = callWithMessage();
System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
System.err.println("Error message: "+e.getMessage());
}
System.exit(0);
}
}# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "El siguiente comando muestra la información de la versión de Thrift instalada.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"tm_list":[
{"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
{"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
{"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
]
}
}'Sample response
You can use the following commands to check the version information of thrift installed;
Domain prompting
Pass a domain prompt in translation_options to tailor the translation style for a specific field. For example, legal or government content calls for formal language, while social media posts work better with a conversational tone.
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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
# --- 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 =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-mt-turbo",
"messages": [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
],
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
}'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
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1'
messages = [
{
"role": "user",
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
}
]
translation_options = {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
response = dashscope.Generation.call(
# 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",
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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder()
.role(Role.USER.getValue())
.content("La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.")
.build();
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
.build();
GenerationParam param = GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
// Note: qwen-mt-lite does not support domain prompting
.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 =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
"model": "qwen-mt-turbo",
"input": {
"messages": [
{
"content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English",
"domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
}
}'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
Use custom prompts with Qwen-MT to control details such as the target language, tone, or domain. Note that this approach is mutually exclusive with the translation_options parameter. If you supply both, translation_options may be ignored.
For the best translation results, use translation_options to configure translation settings instead.
The following example shows a Spanish-to-English legal translation using a detailed prompt:
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"),
# The base_url varies by region. Update it based on the region you use.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.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,
// The base_url varies by region. Update it based on the region you use.
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.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
# The base_url varies by region. Update it based on the region you use.
dashscope.base_http_api_url = 'https://{WorkspaceId}.ap-southeast-1.maas.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 URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.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
Qwen-MT models accept a maximum of 8,192 input tokens. For longer content, use the following strategies to stay within this limit:
-
Translate in segments: Break long text into manageable chunks at natural semantic boundaries -- such as paragraphs or complete sentences -- rather than splitting by character count. This preserves contextual coherence and yields more accurate translations.
-
Provide only the most relevant references: Terms, translation memory entries, and domain prompts all consume input tokens. Include only references directly relevant to the text being translated. Avoid passing large, generic reference lists.
-
-
Set
source_langbased on the scenario-
When the source language is uncertain -- for example, in multilingual chat scenarios -- set
source_langtoauto. The model identifies the language automatically. -
When the source language is known and accuracy is critical -- such as for technical documentation or operation manuals -- always specify
source_langexplicitly. This improves translation accuracy.
-
Supported languages
When sending a request, use either the English name or the Code from the tables below.
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 detailed input and output parameter specifications, see Qwen-MT.