Qwen-MT est un modèle de traduction automatique affiné à partir de Qwen3. Il prend en charge 92 langues, dont le chinois, l'anglais, le japonais, le coréen, le français, l'espagnol, l'allemand, le thaï, l'indonésien, le vietnamien et l'arabe. Il offre également des fonctionnalités d'intervention terminologique, d'invite par domaine et de mémoire de traduction pour maîtriser la qualité des traductions.
Fonctionnement
-
Fournir le texte à traduire : Le tableau
messagesdoit contenir un seul message dont leroleest défini suruser. Lecontentde ce message correspond au texte que vous souhaitez traduire. -
Définir les langues : Spécifiez la langue source (
source_lang) et la langue cible (target_lang) dans le paramètretranslation_options. Pour consulter la liste des langues prises en charge, reportez-vous à la section Langues prises en charge. Pour permettre au modèle de détecter automatiquement la langue source, définissezsource_langsurauto.Préciser la langue source améliore la précision de la traduction.
Vous pouvez également définir la langue à l'aide d'invites personnalisées .
Les exemples suivants montrent comment appeler Qwen-MT à l'aide des SDK Python compatibles OpenAI et 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)
Utilisez le paramètre translation_options pour accéder aux fonctionnalités avancées telles que l'intervention terminologique, la mémoire de traduction et l'invite par domaine.
- Traduction simple uniquement : Conçu spécifiquement pour la traduction, Qwen-MT ne prend pas en charge les conversations multi-tours.
- Messages système non pris en charge : Impossible de définir un comportement global via un message de rôle
system. Configurez plutôt le comportement de traduction dans le paramètretranslation_options.
Choix du modèle
- Pour les scénarios généraux, choisissez
qwen-mt-flash. Ce modèle offre le meilleur équilibre entre qualité, rapidité et coût, tout en prenant en charge la sortie en streaming incrémentiel. - Pour une qualité de traduction optimale dans des domaines professionnels, optez pour
qwen-mt-plus. - Pour la vitesse de réponse la plus élevée dans des scénarios simples et en temps réel, privilégiez
qwen-mt-lite.
Le tableau suivant compare les modèles disponibles.
Modèle | Scénario | Résultat | Vitesse | Coût | Langues prises en charge | Streaming incrémentiel |
|---|---|---|---|---|---|---|
qwen-mt-plus | Fournit une traduction de haute qualité pour des scénarios tels que les domaines professionnels, les documents officiels, les articles universitaires et les rapports techniques | Optimal | Standard | Élevé | 92 | Non pris en charge |
qwen-mt-flash | Recommandé pour un usage général. Convient au contenu de sites web et d'applications, aux descriptions de produits, aux communications quotidiennes et aux articles de blog | Bon | Rapide | Faible | 92 | Pris en charge |
qwen-mt-lite | Scénarios simples sensibles à la latence, comme le chat en temps réel et la traduction de commentaires en direct | Basique | La plus rapide | Le plus faible | 31 | Pris en charge |
Consultez les limites de la fenêtre de contexte et la tarification dans la console. Pour les limites de requêtes simultanées, reportez-vous à la section Modèle de traduction Qwen.
Prise en main
Cette section présente un exemple simple : la traduction de "No me reí después de ver este video" en anglais.
Obtenez une clé API et exportez la clé API en tant que variable d'environnement. Si vous utilisez le SDK OpenAI ou le SDK DashScope pour effectuer vos appels, installez le SDK.
Compatible OpenAI
Exemple de requêteimport 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"
}
}'
I didn't laugh after watching this video.
DashScope
Exemple de requêteImportantLe SDK Java DashScope doit être en version 2.20.6 ou ultérieure.
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: $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"
}
}
}'
I didn't laugh after watching this video.
Sortie en streaming
La sortie en streaming fournit le contenu traduit de manière incrémentielle, ce qui réduit la latence perçue. Actuellement, qwen-mt-flash et qwen-mt-lite prennent en charge le streaming incrémentiel, où chaque réponse contient uniquement le contenu nouvellement généré. Activez cette option avec le paramètre incremental_output. En revanche, qwen-mt-plus ne prend en charge que le streaming non incrémentiel, où chaque réponse renvoie l'intégralité de la traduction générée jusqu'alors. Pour plus d'informations, consultez la section Sortie en streaming.
Compatible OpenAI
Exemple de requêteimport 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"
}
}'
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
Exemple de requêteimport 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 supports this feature.
incremental_output=True,
translation_options=translation_options
)
for chunk in response:
print(chunk.output.choices[0].message.content, end="", flush=True)
// The DashScope SDK must be version 2.20.6 or later.
import java.lang.System;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import io.reactivex.Flowable;
public class Main {
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static void handleGenerationResult(GenerationResult message) {
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
System.out.print(content);
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
private static GenerationParam buildGenerationParam(Message userMsg) {
TranslationOptions options = TranslationOptions.builder()
.sourceLang("auto")
.targetLang("English")
.build();
return GenerationParam.builder()
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-mt-flash")
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.translationOptions(options)
// Enable incremental output. This is supported only by qwen-mt-flash.
.incrementalOutput(true)
.messages(Arrays.asList(userMsg))
.build();
}
public static void main(String[] args) {
try {
// The URL varies by region. Update it based on the region you use.
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
Message userMsg = Message.builder().role(Role.USER.getValue()).content("No me reí después de ver este video").build();
streamCallWithMessage(gen, userMsg);
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}
# ======= Important =======
# The URL varies by region. Update it based on the region you use.
# === Delete this comment before execution ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-mt-flash",
"input": {
"messages": [
{
"content": "No me reí después de ver este video",
"role": "user"
}
]
},
"parameters": {
"translation_options": {
"source_lang": "auto",
"target_lang": "English"
},
"incremental_output":true
}'
I didn't laugh after watching this video.
qwen-mt-plus ne prend pas en charge la sortie en streaming incrémentiel.
Améliorer la qualité de la traduction
La traduction de base convient aux usages courants, tels que les communications informelles. Cependant, pour des tâches professionnelles ou critiques, vous pouvez rencontrer des difficultés spécifiques :
- Terminologie incohérente : les noms de produits ou les termes techniques sont traduits de manière incorrecte ou variable d'un passage à l'autre.
- Style inadapté : le texte traduit ne respecte pas le ton ni les conventions attendues dans un domaine particulier, comme le juridique ou le marketing.
Qwen-MT propose trois fonctionnalités pour résoudre ces problèmes : l'intervention terminologique, la mémoire de traduction et l'incitation par domaine.
Intervention terminologique
Fournissez un glossaire dans le champ terms afin de garantir une traduction systématiquement cohérente des noms de marque, de produit ou des termes techniques.
Pour définir et transmettre votre glossaire :
-
Définir les termes
Créez un tableau JSON et assignez-le au champ
terms. Chaque objet du tableau associe un terme source à sa traduction requise :{ "source": "term", "target": "pre-translated term" } -
Transmettre les termes
Transmettez le paramètre
translation_optionsen y incluant votre tableauterms.
OpenAI compatible
Exemple de requêteimport 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"
}
]
}
}'
Une fois le glossaire ajouté, le résultat de la traduction intègre les termes spécifiés : « biological sensor » et « health status of the body ».
--- [Translation result without terms] ---
This set of biosensors uses graphene, a new material, whose target substance is chemical elements. Its sensitive "sense of smell" allows it to more deeply and accurately reflect one's health condition.
==================================================
--- [Translation result with terms] ---
This biological sensor uses a new material called graphene. Its target is chemical elements, and its sensitive "sense of smell" enables it to reflect the health status of the body more deeply and accurately.
DashScope
Exemple de requêteimport 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: $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"
}
]
}
}
}'
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.
Mémoire de traduction
Si vous souhaitez que le modèle adopte un style de traduction ou une structure de phrase spécifique, fournissez des paires de phrases source-cible comme exemples dans le champ tm_list. Le modèle s'inspire du style de ces paires de référence pour l'appliquer à la traduction en cours. Cette approche est particulièrement utile pour assurer la cohérence de vastes ensembles documentaires ou pour se conformer aux conventions rédactionnelles établies d'une organisation.
-
Définir la mémoire de traduction
Créez un tableau JSON nommé
tm_list. Chaque objet associe une phrase source à sa traduction de référence :{ "source": "source statement", "target": "translated statement" } -
Transmettre la mémoire de traduction
Incluez le paramètre
translation_optionsaccompagné de votre tableau de mémoire de traduction.
L'exemple suivant illustre le fonctionnement de la mémoire de traduction.
OpenAI compatible
Exemple de requêteimport 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:"}
]
}
}'
You can run the following command to view the version of Thrift that is installed:
DashScope
Exemple de requêteimport 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: $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:"}
]
}
}'
You can use the following commands to check the version information of thrift installed;
Invite par domaine
Transmettez une invite de domaine dans translation_options pour adapter le style de traduction à un secteur spécifique. Par exemple, les contenus juridiques ou gouvernementaux requièrent un langage formel, tandis que les publications sur les réseaux sociaux s'accommodent mieux d'un ton conversationnel.
ImportantLes invites par domaine ne prennent actuellement en charge que l'anglais.
Compatible OpenAI
Exemple de requêteimport 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."
}
}'
--- [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
Exemple de requêteimport 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: $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."}
}
}'
The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause.
Invites personnalisées
Utilisez des invites personnalisées avec Qwen-MT pour contrôler des aspects tels que la langue cible, le ton ou le domaine. Notez que cette approche est mutuellement exclusive avec le paramètre translation_options. Si vous fournissez les deux, translation_options risque d'être ignoré.
Pour obtenir les meilleurs résultats de traduction, utilisez plutôt
translation_optionsafin de configurer les paramètres de traduction.
L'exemple suivant illustre une traduction juridique de l'espagnol vers l'anglais à l'aide d'une invite détaillée :
Compatible 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();
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
Exemple de requêteimport 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();
}
}
}
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.
Mise en production
-
Maîtriser le nombre de tokens d'entrée
Les modèles Qwen-MT acceptent un maximum de 8 192 tokens en entrée. Pour les contenus plus longs, adoptez les stratégies suivantes afin de respecter cette limite :
- Traduire par segments : Découpez les textes volumineux en blocs cohérents en suivant des limites sémantiques naturelles, telles que des paragraphes ou des phrases complètes, plutôt qu'en fonction du nombre de caractères. Cette approche préserve la cohérence contextuelle et garantit des traductions plus précises.
- Fournir uniquement les références pertinentes : Les termes, les entrées de mémoire de traduction et les invites spécifiques au domaine consomment tous des tokens d'entrée. N'incluez que les références directement liées au texte à traduire et évitez de transmettre de longues listes génériques.
-
Définirsource_langselon le scénario
- Si la langue source est incertaine, par exemple dans des scénarios de chat multilingue, définissez
source_langsurauto. Le modèle détectera alors automatiquement la langue. - Lorsque la langue source est connue et que la précision est primordiale, comme pour une documentation technique ou des manuels d'utilisation, spécifiez toujours explicitement
source_lang. Cela améliore significativement la qualité de la traduction.
- Si la langue source est incertaine, par exemple dans des scénarios de chat multilingue, définissez
Langues prises en charge
Lors de l'envoi d'une requête, utilisez soit le nom en anglais, soit le Code indiqué dans les tableaux ci-dessous.
En cas de doute sur la langue source, vous pouvez définir le paramètre
source_langsurautopour activer la détection automatique.
Langues prises en charge par qwen-mt-plus/flash/turbo (92)
Langue | Nom en anglais | Code |
|---|---|---|
Anglais | English | en |
Chinois simplifié | Chinese | zh |
Chinois traditionnel | Traditional Chinese | zh_tw |
Russe | Russian | ru |
Japonais | Japanese | ja |
Coréen | Korean | ko |
Espagnol | Spanish | es |
Français | French | fr |
Portugais | Portuguese | pt |
Allemand | German | de |
Italien | Italian | it |
Thaï | Thai | th |
Vietnamien | Vietnamese | vi |
Indonésien | Indonesian | id |
Malais | Malay | ms |
Arabe | Arabic | ar |
Hindi | Hindi | hi |
Hébreu | Hebrew | he |
Birman | Burmese | my |
Tamoul | Tamil | ta |
Ourdou | Urdu | ur |
Bengali | Bengali | bn |
Polonais | Polish | pl |
Néerlandais | Dutch | nl |
Roumain | Romanian | ro |
Turc | Turkish | tr |
Khmer | Khmer | km |
Lao | Lao | lo |
Cantonais | Cantonese | yue |
Tchèque | Czech | cs |
Grec | Greek | el |
Suédois | Swedish | sv |
Hongrois | Hungarian | hu |
Danois | Danish | da |
Finnois | Finnish | fi |
Ukrainien | Ukrainian | uk |
Bulgare | Bulgarian | bg |
Serbe | Serbian | sr |
Télougou | Telugu | te |
Afrikaans | Afrikaans | af |
Arménien | Armenian | hy |
Assamais | Assamese | as |
Asturien | Asturian | ast |
Basque | Basque | eu |
Biélorusse | Belarusian | be |
Bosniaque | Bosnian | bs |
Catalan | Catalan | ca |
Cebuano | Cebuano | ceb |
Croate | Croatian | hr |
Arabe égyptien | Egyptian Arabic | arz |
Estonien | Estonian | et |
Galicien | Galician | gl |
Géorgien | Georgian | ka |
Gujarati | Gujarati | gu |
Islandais | Icelandic | is |
Javanais | Javanese | jv |
Kannada | Kannada | kn |
Kazakh | Kazakh | kk |
Letton | Latvian | lv |
Lituanien | Lithuanian | lt |
Luxembourgeois | Luxembourgish | lb |
Macédonien | Macedonian | mk |
Maithili | Maithili | mai |
Maltais | Maltese | mt |
Marathi | Marathi | mr |
Arabe mésopotamien | Mesopotamian Arabic | acm |
Arabe marocain | Moroccan Arabic | ary |
Arabe najdi | Najdi Arabic | ars |
Népalais | Nepali | ne |
Azerbaïdjanais du Nord | North Azerbaijani | az |
Arabe levantin du Nord | North Levantine Arabic | apc |
Ouzbek du Nord | Northern Uzbek | uz |
Norvégien Bokmål | Norwegian Bokmål | nb |
Norvégien Nynorsk | Norwegian Nynorsk | nn |
Occitan | Occitan | oc |
Odia | Odia | or |
Pangasinan | Pangasinan | pag |
Sicilien | Sicilian | scn |
Sindhi | Sindhi | sd |
Cinghalais | Sinhala | si |
Slovaque | Slovak | sk |
Slovène | Slovenian | sl |
Arabe levantin du Sud | South Levantine Arabic | ajp |
Swahili | Swahili | sw |
Tagalog | Tagalog | tl |
Arabe Ta’izzi-Adeni | Ta’izzi-Adeni Arabic | acq |
Albanais Tosk | Tosk Albanian | sq |
Arabe tunisien | Tunisian Arabic | aeb |
Vénitien | Venetian | vec |
Waray | Waray | war |
Gallois | Welsh | cy |
Persan occidental | Western Persian | fa |
Langues prises en charge par qwen-mt-lite (31)
Langue | Nom en anglais | Code |
|---|---|---|
Anglais | English | en |
Chinois simplifié | Chinese | zh |
Chinois traditionnel | Traditional Chinese | zh_tw |
Russe | Russian | ru |
Japonais | Japanese | ja |
Coréen | Korean | ko |
Espagnol | Spanish | es |
Français | French | fr |
Portugais | Portuguese | pt |
Allemand | German | de |
Italien | Italian | it |
Thaï | Thai | th |
Vietnamien | Vietnamese | vi |
Indonésien | Indonesian | id |
Malais | Malay | ms |
Arabe | Arabic | ar |
Hindi | Hindi | hi |
Hébreu | Hebrew | he |
Ourdou | Urdu | ur |
Bengali | Bengali | bn |
Polonais | Polish | pl |
Néerlandais | Dutch | nl |
Turc | Turkish | tr |
Khmer | Khmer | km |
Tchèque | Czech | cs |
Suédois | Swedish | sv |
Hongrois | Hungarian | hu |
Danois | Danish | da |
Finnois | Finnish | fi |
Tagalog | Tagalog | tl |
Persan | Persian | fa |
Référence API
Pour obtenir les spécifications détaillées des paramètres d'entrée et de sortie, consultez Qwen-MT.