翻译能力(Qwen-MT)

Qwen-MT模型是基于通义千问模型优化的机器翻译大语言模型,支持92个语种(包括中、英、日、韩、法、西、德、泰、印尼、越、阿等)互译。在多语言互译的基础上,提供术语干预、领域提示、记忆库等能力,提升模型在复杂应用场景下的翻译效果。

支持的模型

基于Qwen3全面升级的旗舰级翻译大模型,支持92个语种(包括中、英、日、韩、法、西、德、泰、印尼、越、阿等)互译。性能显著优化,术语定制更稳定,格式还原度更高,领域适配更强,译文精准自然。

如果您对翻译质量有较高要求,建议选择qwen-mt-plus模型;如果您希望翻译速度更快或成本更低,建议选择qwen-mt-turbo模型。

模型名称

上下文长度

最大输入

最大输出

输入成本

输出成本

(Token数)

(每千Token)

qwen-mt-plus

属于Qwen3-MT

4,096

2,048

2,048

0.0018

0.0054

qwen-mt-turbo

属于Qwen3-MT

0.0007

0.00195

使用方法

由于翻译场景的特殊性,Qwen-MT 与通用文本生成模型的使用方法相比有以下不同:

  1. 需要将源语言(source_lang)、目标语言(target_lang)等通过translation_options参数传入。当您不确定翻译原文的语种,或原文多语种混杂时,可以将source_lang设置为"auto",模型会自动判断输入文本的语种。

    具体使用方法请参考下方代码。
  2. 不支持指定 System Message,也不支持多轮对话;messages 数组中有且仅有一个 User Message,用于指定需要翻译的语句。

前提条件

您需要已获取API Key配置API Key到环境变量。如果通过OpenAI SDKDashScope SDK进行调用,还需要安装SDK

DashScope Java SDK 版本需要不低于 2.20.6。

简单示例

OpenAI兼容

此处以将中译英的简单场景为例。通过参考支持的语言,您可以将source_lang参数设为"Chinese"target_lang参数设为"English",需要翻译的语言“我看到这个视频后没有笑”传入 User Message,发起请求后即可得到翻译的结果。

请求示例

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "我看到这个视频后没有笑"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English"
}

completion = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-mt-turbo",
    "messages": [{"role": "user", "content": "看完这个视频我没有笑"}],
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
      }
}'

响应示例

I didn't laugh after watching this video. 

DashScope

此处以将中译英的简单场景为例。通过参考支持的语言,您可以将source_lang参数设为"Chinese"target_lang参数设为"English",需要翻译的语言“我看到这个视频后没有笑”传入 User Message,发起请求后即可得到翻译的结果。

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": "我看到这个视频后没有笑"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
}
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// DashScope SDK 版本需要不低于 2.20.6
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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("我看到这个视频后没有笑")
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼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("错误信息:"+e.getMessage());
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "我看到这个视频后没有笑",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'

响应示例

I didn't laugh after watching this video. 

流式输出

大模型收到输入后并不是一次性生成最终结果,而是逐步地生成中间结果,最终结果由中间结果拼接而成。使用非流式输出方式需要等待模型生成结束后再将生成的中间结果拼接后返回,而流式输出可以实时地将中间结果返回,您可以在模型进行输出的同时进行阅读,减少等待模型回复的时间。

OpenAI兼容

请求示例

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "我看到这个视频后没有笑"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English"
}

completion = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    stream=True,
    extra_body={
        "translation_options": translation_options
    }
)
for chunk in completion:
    print(chunk.choices[0].delta.content)
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-mt-turbo",
    "messages": [{"role": "user", "content": "看完这个视频我没有笑"}],
    "stream": true,
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English"
      }
}'

响应示例

I
I didn
I didn't
I didn't laugh after watching this video
I didn't laugh after watching this video. 
Qwen-MT模型暂时不支持增量式流式输出。

DashScope

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": "我看到这个视频后没有笑"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
}
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",
    messages=messages,
    result_format='message',
    stream=True,
    translation_options=translation_options
)
for chunk in response:
    print(chunk.output.choices[0].message.content)
// DashScope SDK 版本需要不低于 2.20.6
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 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.println(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()
                // 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-mt-plus")
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void main() {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("我看到这个视频后没有笑").build();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException  e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "我看到这个视频后没有笑",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English"
  }
}'

响应示例

I
I didn
I didn't
I didn't laugh after watching this video
I didn't laugh after watching this video. 
Qwen-MT模型暂时不支持增量式流式输出。

术语干预翻译

如果需要翻译的语句中有较多专业术语,直接使用简单示例中的方法可能无法准确翻译。您可以提前对这些术语进行翻译,并将其提供给Qwen-MT模型作为参考,使其能够结合您提供的术语来进行翻译。

术语的定义与传入方法为:

  1. 定义术语数组

    您需要创建一个包含术语的JSON数组terms,每个术语是一个JSON对象,包含术语和翻译过的术语信息,格式如下:

    {
        "source": "术语",
        "target": "提前翻译好的术语"
    }
  2. 传入数组

    通过translation_options参数传入第一步定义好的 terms术语数组。

完成术语的定义与传入后,您可以参考以下代码实现术语干预翻译。

OpenAI兼容

请求示例

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "而这套生物传感器运用了石墨烯这种新型材料,它的目标物是化学元素,敏锐的“嗅觉”让它能更深度、准确地体现身体健康状况。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
        {
            "source": "生物传感器",
            "target": "biological sensor"
        },
        {
            "source": "石墨烯",
            "target": "graphene"
        },
        {
            "source": "化学元素",
            "target": "chemical elements"
        },
        {
            "source": "身体健康状况",
            "target": "health status of the body"
        }
    ]
}

completion = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "messages": [
    {
      "role": "user",
      "content": "而这套生物传感器运用了石墨烯这种新型材料,它的目标物是化学元素,敏锐的“嗅觉”让它能更深度、准确地体现身体健康状况。"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
      {
        "source": "生物传感器",
        "target": "biological sensor"
      },
      {
        "source": "石墨烯",
        "target": "graphene"
      },
      {
        "source": "化学元素",
        "target": "chemical elements"
      },
      {
        "source": "身体健康状况",
        "target": "health status of the body"
      }
    ]
  }
}'

响应示例

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 body. 

DashScope

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": "而这套生物传感器运用了石墨烯这种新型材料,它的目标物是化学元素,敏锐的“嗅觉”让它能更深度、准确地体现身体健康状况。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
        {
            "source": "生物传感器",
            "target": "biological sensor"
        },
        {
            "source": "石墨烯",
            "target": "graphene"
        },
        {
            "source": "化学元素",
            "target": "chemical elements"
        },
        {
            "source": "身体健康状况",
            "target": "health status of the body"
        }
    ]
}
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// DashScope SDK 版本需要不低于 2.20.6
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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("而这套生物传感器运用了石墨烯这种新型材料,它的目标物是化学元素,敏锐的“嗅觉”让它能更深度、准确地体现身体健康状况。")
                .build();
        Term term1 = Term.builder()
                .source("生物传感器")
                .target("biological sensor")
                .build();
        Term term2 = Term.builder()
                .source("石墨烯")
                .target("graphene")
                .build();
        Term term3 = Term.builder()
                .source("化学元素")
                .target("chemical elements")
                .build();
        Term term4 = Term.builder()
                .source("身体健康状况")
                .target("health status of the body")
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .terms(Arrays.asList(term1, term2, term3, term4))
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若没有配置环境变量,请用阿里云百炼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() {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("错误信息:"+e.getMessage());
        }
        System.exit(0);
    }
}
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "而这套生物传感器运用了石墨烯这种新型材料,它的目标物是化学元素,敏锐的“嗅觉”让它能更深度、准确地体现身体健康状况。",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English",
      "terms": [
        {
          "source": "生物传感器",
          "target": "biological sensor"
        },
        {
          "source": "石墨烯",
          "target": "graphene"
        },
        {
          "source": "化学元素",
          "target": "chemical elements"
        },
        {
          "source": "身体健康状况",
          "target": "health status of the body"
        }
      ]
  }
}'

响应示例

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. 

使用翻译记忆

如果您已经有标准的双语句对并且希望大模型在后续翻译时能参考这些标准译文给出结果,可以使用翻译记忆功能。

翻译记忆语句的定义与传入方法为:

  1. 定义翻译记忆数组

    您需要创建一个已翻译句子的JSON数组tm_list,每个JSON对象包含源语句与对应的已翻译的语句,格式如下:

    {
        "source": "源语句",
        "target": "已翻译的语句"
    }
  2. 传入翻译记忆数组

    通过translation_options参数传入第一步定义好的 tm_list翻译记忆数组。

完成翻译记忆语句的定义与传入后,您可以参考以下代码实现翻译记忆功能。

OpenAI兼容

请求示例

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "通过如下命令可以看出安装thrift的版本信息;"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "您可以通过如下方式查看集群的内核版本信息:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "我们云HBase的thrift环境是0.9.0,所以建议客户端的版本也为 0.9.0,可以从这里下载thrift的0.9.0 版本,下载的源码包我们后面会用到,这里需要先安装thrift编译环境,对于源码安装可以参考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": "您可以通过PyPI来安装SDK,安装命令如下:",
            "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-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "messages": [
    {
      "role": "user",
      "content": "通过如下命令可以看出安装thrift的版本信息;"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list":[
          {"source": "您可以通过如下方式查看集群的内核版本信息:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
          {"source": "我们云HBase的thrift环境是0.9.0,所以建议客户端的版本也为 0.9.0,可以从这里下载thrift的0.9.0 版本,下载的源码包我们后面会用到,这里需要先安装thrift编译环境,对于源码安装可以参考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": "您可以通过PyPI来安装SDK,安装命令如下:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
    ]
  }
}'

响应示例

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

DashScope

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": "通过如下命令可以看出安装thrift的版本信息;"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "您可以通过如下方式查看集群的内核版本信息:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "我们云HBase的thrift环境是0.9.0,所以建议客户端的版本也为 0.9.0,可以从这里下载thrift的0.9.0 版本,下载的源码包我们后面会用到,这里需要先安装thrift编译环境,对于源码安装可以参考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": "您可以通过PyPI来安装SDK,安装命令如下:",
            "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
        }
    ]}
response = dashscope.Generation.call(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// DashScope SDK 版本需要不低于 2.20.6
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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("通过如下命令可以看出安装thrift的版本信息;")
                .build();
        Tm tm1 = Tm.builder()
                .source("您可以通过如下方式查看集群的内核版本信息:")
                .target("You can use one of the following methods to query the engine version of a cluster:")
                .build();
        Tm tm2 = Tm.builder()
                .source("我们云HBase的thrift环境是0.9.0,所以建议客户端的版本也为 0.9.0,可以从这里下载thrift的0.9.0 版本,下载的源码包我们后面会用到,这里需要先安装thrift编译环境,对于源码安装可以参考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("您可以通过PyPI来安装SDK,安装命令如下:")
                .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()
                // 若没有配置环境变量,请用阿里云百炼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() {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("错误信息:"+e.getMessage());
        }
        System.exit(0);
    }
}
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "通过如下命令可以看出安装thrift的版本信息;",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English",
      "tm_list":[
          {"source": "您可以通过如下方式查看集群的内核版本信息:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
          {"source": "我们云HBase的thrift环境是0.9.0,所以建议客户端的版本也为 0.9.0,可以从这里下载thrift的0.9.0 版本,下载的源码包我们后面会用到,这里需要先安装thrift编译环境,对于源码安装可以参考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": "您可以通过PyPI来安装SDK,安装命令如下:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
      ]
  }
}'

响应示例

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

领域提示

如果您希望翻译的风格更符合某个领域的特性,如法律、政务领域翻译用语应当严肃正式,社交领域用语应当口语化,可以用一段自然语言文本描述您的领域,将其提供给大模型作为提示。

领域提示语句暂时只支持英文。

通过translation_options参数传入定义好的 domains领域提示语句。

OpenAI兼容

请求示例

import os
from openai import OpenAI

client = OpenAI(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    base_url="https://dashscope.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "第二个SELECT语句返回一个数字,表示在没有LIMIT子句的情况下,第一个SELECT语句返回了多少行。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "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 = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "messages": [
    {
      "role": "user",
      "content": "第二个SELECT语句返回一个数字,表示在没有LIMIT子句的情况下,第一个SELECT语句返回了多少行。"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "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."
  }
}'

响应示例

The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without LIMIT clause. 

DashScope

请求示例

import os
import dashscope

messages = [
    {
        "role": "user",
        "content": "第二个SELECT语句返回一个数字,表示在没有LIMIT子句的情况下,第一个SELECT语句返回了多少行。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "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(
    # 若没有配置环境变量,请用阿里云百炼API Key将下行替换为:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// DashScope SDK 版本需要不低于 2.20.6
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;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("第二个SELECT语句返回一个数字,表示在没有LIMIT子句的情况下,第一个SELECT语句返回了多少行。")
                .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()
                // 若没有配置环境变量,请用阿里云百炼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() {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("错误信息:"+e.getMessage());
        }
        System.exit(0);
    }
}
curl -X POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "第二个SELECT语句返回一个数字,表示在没有LIMIT子句的情况下,第一个SELECT语句返回了多少行。",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "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."}
  }
}'

响应示例

The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause. 

支持的语言

您可以通过下表查看支持的语言、英文全拼与语种编码,英文全拼语种编码可用于在发起请求时指定。

英文全拼

中文全拼

语种编码

English

英语

en

Chinese

简体中文

zh

Traditional Chinese

繁体中文

zh_tw

Russian

俄语

ru

Japanese

日语

ja

Korean

韩语

ko

Spanish

西班牙语

es

French

法语

fr

Portuguese

葡萄牙语

pt

German

德语

de

Italian

意大利语

it

Thai

泰语

th

Vietnamese

越南语

vi

Indonesian

印度尼西亚语

id

Malay

马来语

ms

Arabic

阿拉伯语

ar

Hindi

印地语

hi

Hebrew

希伯来语

he

Burmese

缅甸语

my

Tamil

泰米尔语

ta

Urdu

乌尔都语

ur

Bengali

孟加拉语

bn

Polish

波兰语

pl

Dutch

荷兰语

nl

Romanian

罗马尼亚语

ro

Turkish

土耳其语

tr

Khmer

高棉语

km

Lao

老挝语

lo

Cantonese

粤语

yue

Czech

捷克语

cs

Greek

希腊语

el

Swedish

瑞典语

sv

Hungarian

匈牙利语

hu

Danish

丹麦语

da

Finnish

芬兰语

fi

Ukrainian

乌克兰语

uk

Bulgarian

保加利亚语

bg

Serbian

塞尔维亚语

sr

Telugu

泰卢固语

te

Afrikaans

南非荷兰语

af

Armenian

亚美尼亚语

hy

Assamese

阿萨姆语

as

Asturian

阿斯图里亚斯语

ast

Basque

巴斯克语

eu

Belarusian

白俄罗斯语

be

Bosnian

波斯尼亚语

bs

Catalan

加泰罗尼亚语

ca

Cebuano

宿务语

ceb

Croatian

克罗地亚语

hr

Egyptian Arabic

埃及阿拉伯语

arz

Estonian

爱沙尼亚语

et

Galician

加利西亚语

gl

Georgian

格鲁吉亚语

ka

Gujarati

古吉拉特语

gu

Icelandic

冰岛语

is

Javanese

爪哇语

jv

Kannada

卡纳达语

kn

Kazakh

哈萨克语

kk

Latvian

拉脱维亚语

lv

Lithuanian

立陶宛语

lt

Luxembourgish

卢森堡语

lb

Macedonian

马其顿语

mk

Maithili

马加希语

mai

Maltese

马耳他语

mt

Marathi

马拉地语

mr

Mesopotamian Arabic

美索不达米亚阿拉伯语

acm

Moroccan Arabic

摩洛哥阿拉伯语

ary

Najdi Arabic

内志阿拉伯语

ars

Nepali

尼泊尔语

ne

North Azerbaijani

北阿塞拜疆语

az

North Levantine Arabic

北黎凡特阿拉伯语

apc

Northern Uzbek

北乌兹别克语

uz

Norwegian Bokmål

书面语挪威语

nb

Norwegian Nynorsk

新挪威语

nn

Occitan

奥克语

oc

Odia

奥里亚语

or

Pangasinan

邦阿西楠语

pag

Sicilian

西西里语

scn

Sindhi

信德语

sd

Sinhala

僧伽罗语

si

Slovak

斯洛伐克语

sk

Slovenian

斯洛文尼亚语

sl

South Levantine Arabic

南黎凡特阿拉伯语

ajp

Swahili

斯瓦希里语

sw

Tagalog

他加禄语

tl

Ta’izzi-Adeni Arabic

塔伊兹-亚丁阿拉伯语

acq

Tosk Albanian

托斯克阿尔巴尼亚语

sq

Tunisian Arabic

突尼斯阿拉伯语

aeb

Venetian

威尼斯语

vec

Waray

瓦莱语

war

Welsh

威尔士语

cy

Western Persian

西波斯语

fa

常见问题

Q:如何接入沉浸式翻译

A:在最新版插件添加自定义翻译服务,选择 Qwen MT

image.png

填入 API Key,模型下拉栏选择 qwen-mt-plusqwen-mt-turbo,在左侧边栏将 Qwen MT 设为默认

image.png

前往Qwen3 Technical Report,单击右侧插件小球,进行网页翻译。

image.png

Q:如何接入其它三方工具

A: Dify的最新版通义千问插件已支持Qwen-MT模型。

image.png

其它三方工具是否支持以实际情况为准。

API参考

关于通义千问翻译模型的输入与输出参数,请参考通义千问

错误码

如果模型调用失败并返回报错信息,请参见错误信息进行解决。