QwenCloudBRASIL
Tradução de apoio para consulta. Código e identificadores técnicos preservados. Consultar referência original ↗

Tradução automática (Qwen-MT)

92 idiomas com termos

Qwen-MT é um modelo de tradução de máquina bem ajustado de Qwen3, apoiando 92 idiomas. Fornece intervenção de termo, alerta de domínio e memória de tradução para melhorar a qualidade da tradução.

Como funciona

  1. ? Fornecer o texto para traduzir ? messages O array deve conter uma única mensagem com sua role - Pronto para... user. O content desta mensagem é o texto a ser traduzido.

  2. Defina a língua de origem.source_lang) e língua alvo (target_lang) na translation_options parâmetro. Para uma lista de idiomas suportados, veja [línguas suportadas] (#supported-languages). Para detectar automaticamente a língua de origem, definir source_lang para auto.

Especificar a língua de origem melhora a precisão da tradução. Você também pode definir línguas usando [prontos personalizados] (#custom-prompts).

OpenAI compatible

```python
# 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"}],
  # Since translation_options is not a standard OpenAI parameter, it must be passed in the extra_body parameter.
  extra_body={"translation_options": {"source_lang": "auto", "target_lang": "English"}},
)
```

DashScope

```python
# 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"
)
```

Limitações

Seleção de modelos

Ver a tabela estruturada nos quadros de referência desta página ↓

Para detalhes do modelo, preços e limites de taxa, veja o [Modelo Marketplace] (https://www.qwencloud.com/models).

Começando.

[Pegue uma chave API] (/api-reference/preparation/api-keyE o define como uma variável de ambiente./api-reference/preparation/export-api-key-env). Para usar o SDK, [instale-o] (/api-reference/preparation/install-sdk).

OpenAI compatible

# Pedido de amostra #



  ```python Python
  import os
  from openai import OpenAI

  client = OpenAI(
    # If you have not configured the environment variable, replace the following line with your API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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"
        }
  }'
  ```



 Resposta de amostra

```text
I didn't laugh after watching this video.
```

DashScope

# Pedido de amostra #

O DashScope Java SDK deve ser a versão 2.20.6 ou posterior.

  ```python Python
  import os
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.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 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)
  ```

  ```java Java
  // 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 {
      Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.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 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);
      }
    }
  }
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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"
      }
    }
  }'
  ```



 Resposta de amostra

```text
I didn't laugh after watching this video.
```

Saída de transmissão

Para conceitos de streaming gerais (protocolo SSE, como permitir streaming, faturamento e uso de fichas), veja Streaming output. Esta seção cobre apenas o comportamento de transmissão específico para tradução automática.

Para ativar o streaming, adicione stream: true para sua chamada de tradução. A única diferença entre o padrão de transmissão (/developer-guides/run-and-scale/streaming) está incluindo translation_options:

completion = client.chat.completions.create(
  model="qwen-mt-flash",
  messages=[{"role": "user", "content": "No me reí después de ver este video"}],
  stream=True,
  stream_options={"include_usage": True},
  extra_body={"translation_options": {"source_lang": "auto", "target_lang": "English"}},
)
for chunk in completion:
  if chunk.choices:
    print(chunk.choices[0].delta.content or "", end="", flush=True)

Ver a tabela estruturada nos quadros de referência desta página ↓

Para DashScope, preparar incremental_output=True para permitir streaming incremental em modelos suportados.

Melhore a qualidade da tradução

Para tarefas de tradução profissional, você pode encontrar estas questões:

Você pode usar termo intervenção, memória de tradução, e domínio que nos leva a resolver esses problemas.

Intervenção do prazo

Para garantir a precisão e consistência da tradução quando o texto contém nomes de marcas, nomes de produtos ou termos técnicos, você pode fornecer um glossário no terms Campo. Isso instrui o modelo a usar suas traduções específicas.

Defina e passe os termos:

Define terms

 Crie uma matriz JSON e atribua-a ao `terms` Campo.  Cada objeto no array representa um termo no seguinte formato:

```json
{
  "source": "term",
  "target": "pre-translated term"
}
```

Pass the terms

Use o `translation_options`  parâmetro para passar o definido `terms` Array.

OpenAI compatible

# Pedido de amostra #



  ```python Python
  import os
  from openai import OpenAI

  client = OpenAI(
    # If you have not configured an environment variable, replace the following line with your API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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"
        }
      ]
    }
  }'
  ```



 Resposta de amostra

 Depois de adicionar os termos, o resultado da tradução é consistente com os termos que você passou: "Sensores biológicos**" e "Estado de saúde do corpo**".

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

# Pedido de amostra #



  ```python Python
  import os
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.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 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)
  ```

  ```java Java
  // 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 {
      Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.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);
    }
  }
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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"
          }
        ]
      }
    }
  }'
  ```



 Resposta de amostra

```text
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

Para instruir o modelo a usar um estilo de tradução ou padrão de frase específico, você pode fornecer pares de sentenças de origem-alvo como exemplos no tm_list Campo. O modelo imita o estilo desses exemplos para a tarefa de tradução atual.

Define the translation memory

 Crie um conjunto JSON chamado `tm_list`.  Cada objeto JSON na matriz contém uma frase fonte e sua correspondente frase traduzida no seguinte formato:

```json
{
  "source": "source statement",
  "target": "translated statement"
}
```

Pass the translation memory

Use o `translation_options`  parâmetro para passar o conjunto de memória de tradução.

OpenAI compatible

# Pedido de amostra #



  ```python Python
  import os
  from openai import OpenAI

  client = OpenAI(
    # If you have not configured an environment variable, replace the following line with your API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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:"}
      ]
    }
  }'
  ```



 Resposta de amostra

```text
You can run the following command to view the version of Thrift that is installed:
```

DashScope

# Pedido de amostra #



  ```python Python
  import os
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.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 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)
  ```

  ```java Java
  // 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 {
      Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.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);
    }
  }
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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:"}
        ]
    }
  }'
  ```



 Resposta de amostra

```text
You can use the following commands to check the version information of thrift installed;
```

Domínio a caminho.

Para adaptar o estilo de tradução a um domínio específico, você pode usar o translation_options parâmetro para passar um prompt de domínio. Por exemplo, traduções para domínios legais ou governamentais devem ser formais, enquanto as para mídia social devem ser coloquiais.

O domínio pede que suporte apenas inglês.

OpenAI compatible

# Pedido de amostra #



  ```python Python
  import os
  from openai import OpenAI

  client = OpenAI(
    # If you have not configured an environment variable, replace the following line with your API key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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."
    }
  }'
  ```



 Resposta de amostra

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

# Pedido de amostra #



  ```python Python
  import os
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.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 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)
  ```

  ```java Java
  // 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 {
      Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.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);
    }
  }
  ```

  ```bash curl
  curl -X POST https://maas.qwencloudapi.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."}
    }
  }'
  ```



 Resposta de amostra

```text
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

Usem alertas personalizados em Qwen-MT para especificar detalhes como a linguagem ou estilo. O translation_options Parâmetro e alertas personalizados podem ser passados juntos, mas quando ambos estão definidos, configurações em translation_options (como target_lang e source_lang) ter prioridade sobre as configurações correspondentes no prompt personalizado e irá sobrepor as especificações de linguagem ou estilo no prompt personalizado.

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

Exemplo: Tradução Espanhol-Inglês no domínio legal:

OpenAI compatible

# Pedido de amostra #



  ```python Python
  import os
  from openai import OpenAI

  client = OpenAI(
    # If the environment variable is not configured, replace the following line with your QwenCloud API Key: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://maas.qwencloudapi.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)
  ```

  ```javascript Node.js
  import OpenAI from 'openai';

  const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    baseURL: "https://maas.qwencloudapi.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();
  ```



 Resposta de amostra

```text
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

# Pedido de amostra #



  ```python Python
  import os
  import dashscope

  dashscope.base_http_api_url = 'https://maas.qwencloudapi.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 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)
  ```

  ```java Java
  // 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 {
      Generation gen = new Generation(Protocol.HTTP.getValue(), "https://maas.qwencloudapi.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 any information.\n" +
          "2.  **Precise Terminology**: Use standard legal terms common to the Common Law system.\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 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%s";
      String spanishLegalText = "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.";
      String finalPrompt = String.format(promptTemplate, spanishLegalText);
      Message userMsg = Message.builder()
          .role(Role.USER.getValue())
          .content(finalPrompt)
          .build();
      GenerationParam param = GenerationParam.builder()
          .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();
      }
      }
  }
  ```



 Resposta de amostra

```text
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.
```

Indo ao vivo

O Qwen-MT Modelos têm um limite máximo de entrada de 8.192 fichas. Por longo conteúdo, considere as seguintes estratégias para controlar o número de fichas de entrada:

Linguagens apoiadas

Use o nome inglês ou código da tabela abaixo quando você enviar um pedido.

Se não tem certeza da língua de origem, pode definir o source_lang parâmetro para auto para detecção automática.

qwen-mt-plus/flash (92 languages)

Ver a tabela estruturada nos quadros de referência desta página ↓

qwen-mt-lite (31 languages)

Ver a tabela estruturada nos quadros de referência desta página ↓

Referência da API

Para parâmetros detalhados da API, veja:

Quadros de referência

Tabelas restauradas a partir da referência original; a ordem das colunas e os valores técnicos foram preservados.

Quadro 1

Modelo Cenário Resultado Velocidade Custo Linguagens apoiadas Suporta saída incremental de streaming.
qwen-mt-plus Cenários que exigem alta qualidade de tradução, tais como áreas profissionais, documentos formais, trabalhos acadêmicos, e relatórios técnicos Melhor. Padrão Alto. 92 Sem suporte
qwen-mt-flash Escolha máxima para uso geral.Adequado para cenários como conteúdo de site/app, descrições de produtos, comunicação diária e postagens no blog Bom. Rápido. Baixo. 92 Apoiado.
qwen-mt-lite Cenários simples e sensíveis à latência, como bate-papo em tempo real e tradução de comentários ao vivo. Básico. Mais rápido. Mais baixo. 31 Apoiado.

Quadro 2

Modelo Fluxos incrementais
qwen-mt-flash, qwen-mt-lite Apoiado. Cada pedaço contém apenas conteúdo novo.
qwen-mt-plus Não suportada. Cada pedaço contém todo o conteúdo gerado até agora.