Todos los productos
Search
Centro de documentos

Alibaba Cloud Model Studio:Traducción automática (Qwen-MT)

Última actualización: Oct 12, 2026

Qwen-MT es un modelo de traducción automática ajustado a partir de Qwen3. Admite 92 idiomas (incluidos chino, inglés, japonés, coreano, francés, español, alemán, tailandés, indonesio, vietnamita y árabe) y ofrece intervención de términos, prompting de dominio y memoria de traducción para controlar la calidad de la traducción.

Funcionamiento

  1. Proporcione el texto a traducir: El arreglo messages debe contener un único mensaje con su role establecido en user. El content de este mensaje es el texto que usted want traducir.

  2. Configure los idiomas: Especifique el idioma de origen (source_lang) y el idioma de destino (target_lang) en el parámetro translation_options. Para ver una lista de idiomas admitidos, consulte Idiomas admitidos. Para permitir que el modelo detecte automáticamente el idioma de origen, establezca source_lang en auto.

    Especificar el idioma de origen mejora la precisión de la traducción.

    También puede configurar el idioma mediante prompts personalizados .

Los siguientes ejemplos muestran cómo llamar a Qwen-MT utilizando los SDK de Python compatibles con OpenAI y 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)

Utilice el parámetro translation_options para acceder a funciones avanzadas de traducción, como intervención de términos, memoria de traducción y prompting de dominio.

Limitaciones
  • Solo traducción de turno único: Qwen-MT está diseñado específicamente para traducción y no admite conversaciones de múltiples turnos.
  • Mensajes del sistema no admitidos: No puede configurar el comportamiento global mediante un mensaje con rol system. En su lugar, configure el comportamiento de traducción en el parámetro translation_options.

Selección de modelo

  • Para escenarios generales, elija qwen-mt-flash. Ofrece el mejor equilibrio entre calidad, velocidad y costo, y admite salida en streaming incremental.
  • Para la mayor calidad de traducción en dominios profesionales, elija qwen-mt-plus.
  • Para la velocidad de respuesta más rápida en escenarios simples y en tiempo real, elija qwen-mt-lite.

La siguiente tabla compara los modelos disponibles.

Modelo

Escenario

Resultado

Velocidad

Costo

Idiomas admitidos

Transmisión incremental

qwen-mt-plus

Proporciona traducción de alta calidad para escenarios como campos profesionales, documentos formales, artículos académicos e informes técnicos

Óptima

Estándar

Alta

92

No compatible

qwen-mt-flash

Recomendado para uso general. Adecuado para contenido de sitios web y aplicaciones, descripciones de productos, comunicación diaria y publicaciones de blogs

Buena

Rápida

Bajo

92

Compatible

qwen-mt-lite

Escenarios simples y sensibles a la latencia, como chat en tiempo real y traducción de comentarios en vivo

Básica

Más rápida

Más baja

31

Compatible

Consulte los límites de la ventana de contexto y los precios en la consola. Para conocer los límites de solicitudes concurrentes, consulte Modelo de traducción Qwen. Para obtener detalles sobre la facturación del modelo de traducción, consulte Precios de inferencia de modelos.

Introducción

Esta sección presenta un ejemplo sencillo: traducir "No me reí después de ver este video" al inglés.

Obtenga una clave de API y exporte la clave de API como variable de entorno. Si utiliza el SDK de OpenAI o el SDK de DashScope para realizar llamadas, instale el SDK.

Compatible con OpenAI

Solicitud de ejemplo
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"
      }
}'
Respuesta de ejemplo
I didn't laugh after watching this video.

DashScope

Solicitud de ejemplo

ImportanteEl SDK de Java de DashScope debe ser versión 2.20.6 o 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-flash",  # This example uses qwen-mt-flash. 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-flash",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'
Respuesta de ejemplo
I didn't laugh after watching this video.

Salida por secuencias

La salida en streaming entrega el contenido traducido de forma incremental, reduciendo la latencia percibida. Actualmente, qwen-mt-flash y qwen-mt-lite admiten streaming incremental, donde cada respuesta contiene únicamente el contenido recién generado. Habilítelo con el parámetro incremental_output. qwen-mt-plus solo admite streaming no incremental, donde cada respuesta devuelve la traducción completa hasta ese momento. Para más información, consulte Salida en streaming.

Compatible con OpenAI

Solicitud de ejemplo
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"
      }
}'
Respuesta de ejemplo
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

Solicitud de ejemplo
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-flash. 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
  }
}'
Respuesta de ejemplo
I didn't laugh after watching this video.

qwen-mt-plus no admite salida de transmisión incremental.

Mejorar la calidad de la traducción

La traducción básica funciona bien para casos de uso cotidianos, como la comunicación informal. Para tareas de traducción profesional o de alta importancia, puede encontrarse con desafíos específicos:

  • Terminología inconsistente: Los nombres de productos o términos específicos de la industria se traducen incorrectamente o de manera inconsistente en diferentes pasajes.
  • Estilo no coincidente: El texto traducido no coincide con el tono o las convenciones esperadas en un dominio específico, como contenido legal o de marketing.

Qwen-MT proporciona tres funciones para abordar estos desafíos: intervención de términos, memoria de traducción y prompting de dominio.

Intervención de términos

Proporcione un glosario en el campo terms para garantizar que los nombres de marcas, nombres de productos o términos técnicos se traduzcan de manera consistente en todo momento.

Para definir y pasar su glosario:

  1. Definir términos

    Cree un arreglo JSON y asígnelo al campo terms. Cada objeto en el arreglo asigna un término de origen a su traducción requerida:

{
    "source": "term",
    "target": "pre-translated term"
}
  1. Pasar los términos

    Pase el parámetro translation_options con su arreglo terms incluido.

Compatible con OpenAI

Solicitud de ejemplo
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-flash",
    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-flash",
    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-flash",
  "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"
      }
    ]
  }
}'
Respuesta de ejemplo

Después de agregar el glosario, la salida de traducción refleja los términos especificados: "sensor biológico" y "estado de salud del cuerpo".

--- [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

Solicitud de ejemplo
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-flash",  # This example uses qwen-mt-flash. 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-flash",
  "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"
        }
      ]
    }
  }
}'
Respuesta de ejemplo
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.

Memoria de traducción

Cuando necesite que el modelo siga un estilo de traducción o patrón de oraciones específico, proporcione pares de oraciones origen-destino como ejemplos en el campo tm_list. El modelo aprende del estilo de estos pares de referencia y lo aplica a la traducción actual. Esto resulta útil para mantener la coherencia en grandes conjuntos de documentación o al adaptarse a las convenciones de redacción establecidas de una organización.

  1. Definir la memoria de traducción

    Cree un arreglo JSON llamado tm_list. Cada objeto empareja una oración de origen con su traducción de referencia:

{
    "source": "source statement",
    "target": "translated statement"
}
  1. Pasar la memoria de traducción

    Incluya el parámetro translation_options con su arreglo de memoria de traducción.

El siguiente ejemplo demuestra la memoria de traducción en acción.

Compatible con OpenAI

Solicitud de ejemplo
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-flash",
  "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:"}
    ]
  }
}'
Respuesta de ejemplo
You can run the following command to view the version of Thrift that is installed:

DashScope

Solicitud de ejemplo
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-flash",  # This example uses qwen-mt-flash. 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-flash",
  "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:"}
      ]
    }
  }
}'
Respuesta de ejemplo
You can use the following commands to check the version information of thrift installed;

Prompting de dominio

Pase un prompt de dominio en translation_options para adaptar el estilo de traducción a un campo específico. Por ejemplo, el contenido legal o gubernamental requiere un lenguaje formal, mientras que las publicaciones en redes sociales funcionan mejor con un tono conversacional.

ImportanteLos prompts de dominio actualmente solo admiten inglés.

Compatible con OpenAI

Solicitud de ejemplo
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-flash",
  "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."
  }
}'
Respuesta de ejemplo
--- [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

Solicitud de ejemplo
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-flash",
    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-flash",
  "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."}
  }
}'
Respuesta de ejemplo
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

Utilice prompts personalizados con Qwen-MT para controlar detalles como el idioma de destino, el tono o el dominio. El parámetro translation_options y los prompts personalizados pueden pasarse juntos, pero cuando ambos se configuran simultáneamente, los ajustes en translation_options (como target_lang, source_lang, etc.) tienen prioridad sobre los ajustes correspondientes en el prompt personalizado y anularán las especificaciones de idioma o estilo definidas en dicho prompt.

Para obtener los mejores resultados de traducción, utilice translation_options para configurar los ajustes de traducción.

El siguiente ejemplo muestra una traducción legal del español al inglés utilizando un prompt detallado:

Compatible con OpenAI

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();
Respuesta de ejemplo
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

Solicitud de ejemplo
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();
        }
        }
}
Respuesta de ejemplo
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.

Puesta en marcha

  • Controlar el recuento de tokens de entrada

    Los modelos Qwen-MT aceptan un máximo de 8,192 tokens de entrada. Para contenido más extenso, utilice las siguientes estrategias para mantenerse dentro de este límite:

    • Traduzca por segmentos: Divida textos largos en fragmentos manejables siguiendo límites semánticos naturales (como párrafos u oraciones completas) en lugar de dividir por recuento de caracteres. Esto preserva la coherencia contextual y produce traducciones más precisas.
    • Proporcione solo las referencias más relevantes: Los términos, las entradas de memoria de traducción y los prompts de dominio consumen tokens de entrada. Incluya únicamente referencias directamente relevantes al texto que se está traduciendo. Evite pasar listas de referencias grandes y genéricas.
  • Configurarsource_langsegún el escenario

    • Cuando el idioma de origen es incierto (por ejemplo, en escenarios de chat multilingüe), configure source_lang como auto. El modelo identifica el idioma automáticamente.
    • Cuando se conoce el idioma de origen y la precisión es crítica (como en documentación técnica o manuales de operación), especifique siempre source_lang explícitamente. Esto mejora la precisión de la traducción.

Idiomas admitidos

Al enviar una solicitud, utilice el nombre en inglés o el código de las tablas a continuación.

Si no está seguro del idioma de origen, puede configurar el parámetro source_lang en auto para la detección automática.

Idiomas admitidos por qwen-mt-plus/flash/turbo (92)

Idioma

Nombre en inglés

Code

Inglés

Inglés

en

Chino simplificado

Chino

zh

Chino tradicional

Chino tradicional

zh_tw

Ruso

Ruso

ru

Japonés

Japonés

ja

Coreano

Coreano

ko

Español

Español

es

Francés

Francés

fr

Portugués

Portugués

pt

Alemán

Alemán

de

Italiano

Italiano

it

Tailandés

Tailandés

th

Vietnamita

Vietnamita

vi

Indonesio

Indonesio

id

Malayo

Malayo

ms

Árabe

Árabe

ar

Hindi

Hindi

hi

Hebreo

Hebreo

he

Birmano

Birmano

my

Tamil

Tamil

ta

Urdu

Urdu

ur

Bengalí

Bengalí

bn

Polaco

Polaco

pl

Neerlandés

Neerlandés

nl

Rumano

Rumano

ro

Turco

Turco

tr

Jemer

Jemer

km

Lao

Lao

lo

Cantonés

Cantonés

yue

Checo

Checo

cs

Griego

Griego

el

Sueco

Sueco

sv

Húngaro

Húngaro

hu

Danés

Danés

da

Finlandés

Finlandés

fi

Ucraniano

Ucraniano

uk

Búlgaro

Búlgaro

bg

Serbio

Serbio

sr

Telugu

Telugu

te

Afrikáans

Afrikáans

af

Armenio

Armenio

hy

Asamés

Asamés

as

Asturiano

Asturiano

ast

Vasco

Vasco

eu

Bielorruso

Bielorruso

be

Bosnio

Bosnio

bs

Catalán

Catalán

ca

Cebuano

Cebuano

ceb

Croata

Croata

hr

Árabe egipcio

Árabe egipcio

arz

Estonio

Estonio

et

Gallego

Gallego

gl

Georgiano

Georgiano

ka

Guyaratí

Guyaratí

gu

Islandés

Islandés

is

Javanés

Javanés

jv

Canarés

Canarés

kn

Kazajo

Kazajo

kk

Letón

Letón

lv

Lituano

Lituano

lt

Luxemburgués

Luxemburgués

lb

Macedonio

Macedonio

mk

Maithili

Maithili

mai

Maltés

Maltés

mt

Maratí

Maratí

mr

Árabe mesopotámico

Árabe mesopotámico

acm

Árabe marroquí

Árabe marroquí

ary

Árabe najdí

Árabe najdí

ars

Nepalí

Nepalí

ne

Azerbaiyano septentrional

Azerbaiyano septentrional

az

Árabe levantino septentrional

Árabe levantino septentrional

apc

Uzbeko septentrional

Uzbeko septentrional

uz

Noruego bokmål

Noruego bokmål

nb

Noruego nynorsk

Noruego nynorsk

nn

Occitano

Occitano

oc

Odia

Odia

or

Pangasinense

Pangasinense

pag

Siciliano

Siciliano

scn

Sindhi

Sindhi

sd

Cingalés

Cingalés

si

Eslovaco

Eslovaco

sk

Esloveno

Esloveno

sl

Árabe levantino meridional

Árabe levantino meridional

ajp

Suajili

Suajili

sw

Tagalo

Tagalo

tl

Árabe ta'izzi-adení

Árabe ta'izzi-adení

acq

Albanés tosk

Albanés tosk

sq

Árabe tunecino

Árabe tunecino

aeb

Véneto

Véneto

vec

Valaisano

Waray

war

Galés

Galés

cy

Persa occidental

Persa occidental

fa

Idiomas admitidos por qwen-mt-lite (31)

Idioma

Nombre en inglés

Code

Inglés

Inglés

en

Chino simplificado

Chino

zh

Chino tradicional

Chino tradicional

zh_tw

Ruso

Ruso

ru

Japonés

Japonés

ja

Coreano

Coreano

ko

Español

Español

es

Francés

Francés

fr

Portugués

Portugués

pt

Alemán

Alemán

de

Italiano

Italiano

it

Tailandés

Tailandés

th

Vietnamita

Vietnamita

vi

Indonesio

Indonesio

id

Malayo

Malayo

ms

Árabe

Árabe

ar

Hindi

Hindi

hi

Hebreo

Hebreo

he

Urdu

Urdu

ur

Bengalí

Bengalí

bn

Polaco

Polaco

pl

Neerlandés

Neerlandés

nl

Turco

Turco

tr

Jemer

Jemer

km

Checo

Checo

cs

Sueco

Sueco

sv

Húngaro

Húngaro

hu

Danés

Danés

da

Finlandés

Finlandés

fi

Tagalo

Tagalo

tl

Persa

Persa

fa

Referencia de API

Para obtener especificaciones detalladas de los parámetros de entrada y salida, consulte Qwen-MT.