Todos os produtos
Search
Central de documentação

Alibaba Cloud Model Studio:Tradução automática (Qwen-MT)

Última atualização: Sep 09, 2026

O Qwen-MT é um modelo de tradução automática ajustado a partir do Qwen3. Ele oferece suporte a 92 idiomas — incluindo chinês, inglês, japonês, coreano, francês, espanhol, alemão, tailandês, indonésio, vietnamita e árabe — e disponibiliza intervenção de termos, prompting de domínio e memória de tradução para controlar a qualidade da tradução.

Como funciona

  1. Forneça o texto para tradução: O array messages deve conter uma única mensagem com role definido como user. O content dessa mensagem corresponde ao texto que você deseja traduzir.

  2. Defina os idiomas: Especifique o idioma de origem (source_lang) e o idioma de destino (target_lang) no parâmetro translation_options. Para obter a lista de idiomas suportados, consulte Supported languages. Para permitir que o modelo detecte o idioma de origem automaticamente, defina source_lang como auto.

    Especificar o idioma de origem melhora a precisão da tradução.

    Você também pode definir o idioma usando custom prompts .

Os exemplos a seguir mostram como chamar o Qwen-MT usando os SDKs Python compatíveis com OpenAI e DashScope.

# 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"}},
)
# 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"
)
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-flash",
    # 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"
        }
    },
)
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-flash",
    # 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 o parâmetro translation_options para acessar recursos avançados de tradução, como term intervention, translation memory e domain prompting.

Limitações
  • Apenas tradução de turno único: O Qwen-MT foi desenvolvido especificamente para tradução e não oferece suporte a conversas de múltiplos turnos.
  • Mensagens de sistema não suportadas: Não é possível definir comportamento global por meio de uma mensagem com função system. Em vez disso, configure o comportamento da tradução no parâmetro translation_options.

Seleção de modelo

  • Para cenários gerais, escolha qwen-mt-flash. Este modelo oferece o melhor equilíbrio entre qualidade, velocidade e custo, além de suportar saída em streaming incremental.
  • Para obter a maior qualidade de tradução em domínios profissionais, escolha qwen-mt-plus.
  • Para garantir a velocidade de resposta mais rápida em cenários simples e em tempo real, escolha qwen-mt-lite.

A tabela a seguir compara os modelos disponíveis.

Modelo

Cenário

Resultado

Velocidade

Custo

Idiomas suportados

Streaming incremental

qwen-mt-plus

Oferece tradução de alta qualidade para cenários como campos profissionais, documentos formais, artigos acadêmicos e relatórios técnicos

Melhor

Padrão

Alto

92

Não suportado

qwen-mt-flash

Recomendado para uso geral. Adequado para conteúdo de sites e aplicativos, descrições de product, comunicação diária e postagens de blog

Bom

Rápida

Baixo

92

Suportado

qwen-mt-turbo

Este modelo não receberá atualizações futuras. Use o flash em seu lugar.

Regular

Rápida

Baixo

92

Não suportado

qwen-mt-lite

Cenários simples e sensíveis à latência, como chat em tempo real e tradução de comentários ao vivo

Básico

Mais rápida

Mais baixo

31

Suportado

Verifique os limites da janela de contexto e os preços no console. Para limites de solicitações simultâneas, consulte Qwen translation model.

Primeiros passos

Esta seção apresenta um exemplo simples: traduzir "No me reí después de ver este video" para o inglês.

Obtain an API key e export the API key as an environment variable. Se você usar o SDK OpenAI ou DashScope para fazer chamadas, install the SDK.

OpenAI compatible

Exemplo de solicitação
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"
      }
}'
Exemplo de resposta
I didn't laugh after watching this video.

DashScope

Exemplo de solicitação

ImportanteO SDK Java do DashScope deve ser da versão 2.20.6 ou posterior.

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: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'
Exemplo de resposta
I didn't laugh after watching this video.

Saída em streaming

A saída em streaming entrega o conteúdo traduzido de forma incremental, reduzindo a latência percebida. Atualmente, o qwen-mt-flash e o qwen-mt-lite suportam streaming incremental, em que cada resposta contém apenas o conteúdo recém-gerado. Ative esse recurso com o parâmetro incremental_output. Já o qwen-mt-plus e o qwen-mt-turbo suportam apenas streaming não incremental, onde cada resposta retorna a tradução completa até o momento. Para mais informações, consulte Streaming output.

OpenAI compatible

Exemplo de solicitação
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"
      }
}'
Exemplo de resposta
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

Exemplo de solicitação
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 and qwen-mt-lite support 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 and qwen-mt-lite.
                .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: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
  "model": "qwen-mt-flash",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    },
    "incremental_output": true
  }
}'
Exemplo de resposta
I didn't laugh after watching this video.

O qwen-mt-plus e o qwen-mt-turbo não suportam saída em streaming incremental.

Melhorar a qualidade da tradução

A tradução básica funciona bem para casos de uso cotidianos, como comunicação informal. Para tarefas de tradução profissional ou de alta complexidade, você pode enfrentar desafios específicos:

  • Terminologia inconsistente: Nomes de product ou termos específicos do setor são traduzidos incorretamente ou apresentam inconsistências entre diferentes trechos.
  • Estilo incompatível: O texto traduzido não corresponde ao tom ou às convenções esperadas em um domínio específico, como conteúdo jurídico ou de marketing.

O Qwen-MT oferece três recursos para lidar com esses desafios: intervenção de termos, memória de tradução e prompting de domínio.

Intervenção de termos

Forneça um glossário no campo terms para garantir que nomes de marcas, nomes de product ou termos técnicos sejam traduzidos de forma consistente todas as vezes.

Para definir e passar seu glossário:

  1. Defina os termos

    Crie um array JSON e atribua-o ao campo terms. Cada objeto no array mapeia um termo de source para sua tradução obrigatória:

{
    "source": "term",
    "target": "pre-translated term"
}
  1. Passe os termos

    Passe o parâmetro translation_options com seu array terms incluído.

OpenAI compatible

Exemplo de solicitação
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"
      }
    ]
  }
}'
Exemplo de resposta

Após adicionar o glossário, a saída da tradução reflete os termos especificados: "biological sensor" e "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

Exemplo de solicitação
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: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English",
      "terms": [
        {
          "source": "biosensor",
          "target": "biological sensor"
        },
        {
          "source": "estado de salud del cuerpo",
          "target": "health status of the body"
        }
      ]
    }
  }
}'
Exemplo de resposta
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.

Memória de tradução

Quando você precisa que o modelo siga um estilo de tradução ou padrão de frase específico, forneça pares de frases source-destino como exemplos no campo tm_list. O modelo aprende com o estilo desses pares de referência e o aplica à tradução atual. Isso é útil para manter a consistência em grandes conjuntos de documentação ou ao adaptar-se às convenções de redação estabelecidas por uma organização.

  1. Defina a memória de tradução

    Crie um array JSON chamado tm_list. Cada objeto associa uma frase de source à sua tradução de referência:

{
    "source": "source statement",
    "target": "translated statement"
}
  1. Passe a memória de tradução

    Inclua o parâmetro translation_options com seu array de memória de tradução.

O exemplo a seguir demonstra a memória de tradução em ação.

OpenAI compatible

Exemplo de solicitação
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:"}
    ]
  }
}'
Exemplo de resposta
You can run the following command to view the version of Thrift that is installed:

DashScope

Exemplo de solicitação
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: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "El siguiente comando muestra la información de la versión de Thrift instalada.",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English",
      "tm_list":[
          {"source": "Puede utilizar uno de los siguientes métodos para consultar la versión del motor de un clúster:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
          {"source": "La versión de Thrift utilizada por nuestro HBase en la nube es la 0.9.0. Por lo tanto, recomendamos que la versión del cliente también sea la 0.9.0. Puede descargar Thrift 0.9.0 desde aquí. El paquete de código fuente descargado se utilizará posteriormente. Primero debe instalar el entorno de compilación de Thrift. Para la instalación desde el código fuente, puede consultar el sitio web oficial de Thrift.", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
          {"source": "Puede instalar el SDK a través de PyPI. El comando de instalación es el siguiente:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
      ]
    }
  }
}'
Exemplo de resposta
You can use the following commands to check the version information of thrift installed;

Prompting de domínio

Passe um prompt de domínio em translation_options para adaptar o estilo da tradução a um campo específico. Por exemplo, conteúdo jurídico ou governamental exige linguagem formal, enquanto postagens em redes sociais funcionam melhor com um tom coloquial.

ImportanteAtualmente, os prompts de domínio suportam apenas inglês.

OpenAI compatible

Exemplo de solicitação
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."
  }
}'
Exemplo de resposta
--- [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

Exemplo de solicitação
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: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English",
      "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
  }
}'
Exemplo de resposta
The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause.

Prompts personalizados

Use prompts personalizados com o Qwen-MT para controlar detalhes como idioma de destino, tom ou domínio. O parâmetro translation_options e os prompts personalizados podem ser passados juntos, mas quando ambos são definidos simultaneamente, as configurações em translation_options (como target_lang, source_lang, etc.) têm prioridade sobre as configurações correspondentes no prompt personalizado e substituirão as especificações de idioma ou estilo presentes nele.

Para obter os melhores resultados de tradução, use translation_options para configurar as definições de tradução.

O exemplo a seguir mostra uma tradução jurídica do espanhol para o inglês usando um prompt detalhado:

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();
Exemplo de resposta
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

Exemplo de solicitação
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();
        }
        }
}
Exemplo de resposta
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.

Entrando em produção

  • Controle a contagem de tokens de entrada

    Os modelos Qwen-MT aceitam no máximo 8.192 tokens de entrada. Para conteúdos mais longos, use as seguintes estratégias para permanecer dentro desse limite:

    • Traduza em segmentos: Divida textos longos em blocos gerenciáveis em limites semânticos naturais — como parágrafos ou frases completas — em vez de dividir pela contagem de caracteres. Isso preserva a coerência contextual e gera traduções mais precisas.
    • Forneça apenas as referências mais relevantes: Termos, entradas de memória de tradução e prompts de domínio consomem tokens de entrada. Inclua apenas referências diretamente relevantes ao texto sendo traduzido. Evite passar listas de referências grandes e genéricas.
  • Definasource_langcom base no cenário
    • Quando o idioma de source for incerto — por exemplo, em cenários de chat multilíngue — defina source_lang como auto. O modelo identifica o idioma automaticamente.
    • Quando o idioma de source for conhecido e a precisão for crítica — como em documentação técnica ou manuais operacionais — sempre especifique source_lang explicitamente. Isso melhora a precisão da tradução.

Idiomas suportados

Ao enviar uma solicitação, use o Nome em inglês ou o Código das tabelas abaixo.

Se você não tiver certeza sobre o idioma de source, pode definir o parâmetro source_lang como auto para detecção automática.

Languages supported by qwen-mt-plus/flash/turbo (92)

Idioma

Nome em inglês

Código

Inglês

English

en

Chinês simplificado

Chinese

zh

Chinês tradicional

Traditional Chinese

zh_tw

Russo

Russian

ru

Japonês

Japanese

ja

Coreano

Korean

ko

Espanhol

Spanish

es

Francês

French

fr

Português

Portuguese

pt

Alemão

German

de

Italiano

Italian

it

Tailandês

Thai

th

Vietnamita

Vietnamese

vi

Indonésio

Indonesian

id

Malaio

Malay

ms

Árabe

Arabic

ar

Hindi

Hindi

hi

Hebraico

Hebrew

he

Birmanês

Burmese

my

Tâmil

Tamil

ta

Urdu

Urdu

ur

Bengali

Bengali

bn

Polonês

Polish

pl

Holandês

Dutch

nl

Romeno

Romanian

ro

Turco

Turkish

tr

Khmer

Khmer

km

Laosiano

Lao

lo

Cantonês

Cantonese

yue

Tcheco

Czech

cs

Grego

Greek

el

Sueco

Swedish

sv

Húngaro

Hungarian

hu

Dinamarquês

Danish

da

Finlandês

Finnish

fi

Ucraniano

Ukrainian

uk

Búlgaro

Bulgarian

bg

Sérvio

Serbian

sr

Télugo

Telugu

te

Africâner

Afrikaans

af

Armênio

Armenian

hy

Assamês

Assamese

as

Asturiano

Asturian

ast

Basco

Basque

eu

Bielorrusso

Belarusian

be

Bósnio

Bosnian

bs

Catalão

Catalan

ca

Cebuano

Cebuano

ceb

Croata

Croatian

hr

Árabe egípcio

Egyptian Arabic

arz

Estoniano

Estonian

et

Galego

Galician

gl

Georgiano

Georgian

ka

Guzerate

Gujarati

gu

Islandês

Icelandic

is

Javanês

Javanese

jv

Canarês

Kannada

kn

Cazaque

Kazakh

kk

Letão

Latvian

lv

Lituano

Lithuanian

lt

Luxemburguês

Luxembourgish

lb

Macedônio

Macedonian

mk

Maithili

Maithili

mai

Maltês

Maltese

mt

Marata

Marathi

mr

Árabe mesopotâmico

Mesopotamian Arabic

acm

Árabe marroquino

Moroccan Arabic

ary

Árabe najdi

Najdi Arabic

ars

Nepalês

Nepali

ne

Azerbaijano do norte

North Azerbaijani

az

Árabe levantino do norte

North Levantine Arabic

apc

Uzbeque do norte

Northern Uzbek

uz

Norueguês bokmål

Norwegian Bokmål

nb

Norueguês nynorsk

Norwegian Nynorsk

nn

Occitano

Occitan

oc

Oriá

Odia

or

Pangasinan

Pangasinan

pag

Siciliano

Sicilian

scn

Sindi

Sindhi

sd

Cingalês

Sinhala

si

Eslovaco

Slovak

sk

Esloveno

Slovenian

sl

Árabe levantino do sul

South Levantine Arabic

ajp

Suaíli

Swahili

sw

Tagalo

Tagalog

tl

Árabe taizi-adeni

Ta’izzi-Adeni Arabic

acq

Albanês tosk

Tosk Albanian

sq

Árabe tunisiano

Tunisian Arabic

aeb

Vêneto

Venetian

vec

Valaisano

Waray

war

Galês

Welsh

cy

Persa ocidental

Western Persian

fa

Languages supported by qwen-mt-lite (31)

Idioma

Nome em inglês

Código

Inglês

English

en

Chinês simplificado

Chinese

zh

Chinês tradicional

Traditional Chinese

zh_tw

Russo

Russian

ru

Japonês

Japanese

ja

Coreano

Korean

ko

Espanhol

Spanish

es

Francês

French

fr

Português

Portuguese

pt

Alemão

German

de

Italiano

Italian

it

Tailandês

Thai

th

Vietnamita

Vietnamese

vi

Indonésio

Indonesian

id

Malaio

Malay

ms

Árabe

Arabic

ar

Hindi

Hindi

hi

Hebraico

Hebrew

he

Urdu

Urdu

ur

Bengali

Bengali

bn

Polonês

Polish

pl

Holandês

Dutch

nl

Turco

Turkish

tr

Khmer

Khmer

km

Tcheco

Czech

cs

Sueco

Swedish

sv

Húngaro

Hungarian

hu

Dinamarquês

Danish

da

Finlandês

Finnish

fi

Tagalo

Tagalog

tl

Persa

Persian

fa

Referência da API

Para especificações detalhadas dos parâmetros de entrada e saída, consulte Qwen-MT.