All Products
Search
Document Center

Alibaba Cloud Model Studio:Penerjemahan mesin (Qwen-MT)

Last Updated:Sep 09, 2026

Qwen-MT adalah model penerjemahan mesin yang telah disesuaikan dari Qwen3. Model ini mendukung 92 bahasa — termasuk Tiongkok, Inggris, Jepang, Korea, Prancis, Spanyol, Jerman, Thailand, Indonesia, Vietnam, dan Arab — serta menyediakan intervensi istilah, prompting domain, dan memori terjemahan untuk mengontrol kualitas terjemahan.

Cara kerja

  1. Sediakan teks yang akan diterjemahkan: Array messages harus berisi satu pesan dengan role-nya diatur ke user. content dari pesan ini adalah teks yang ingin Anda terjemahkan.

  2. Tentukan bahasa: Tentukan bahasa sumber (source_lang) dan bahasa target (target_lang) dalam parameter translation_options. Untuk daftar bahasa yang didukung, lihat Bahasa yang didukung. Untuk membiarkan model mendeteksi bahasa sumber secara otomatis, atur source_lang ke auto.

    Menentukan bahasa sumber meningkatkan akurasi terjemahan.

    Anda juga dapat menyetel bahasa menggunakan prompt kustom.

Contoh berikut menunjukkan cara memanggil Qwen-MT menggunakan SDK Python kompatibel OpenAI dan DashScope.

# Impor dependensi dan buat client...
completion = client.chat.completions.create(
    model="qwen-mt-flash",    # Pilih model
    # Parameter messages harus hanya berisi satu pesan dengan role diatur ke user, dan content-nya adalah teks yang akan diterjemahkan.
    messages=[{"role": "user", "content": "No me reí después de ver este video"}],
    # Karena translation_options bukan parameter standar OpenAI, parameter ini harus dilewatkan melalui parameter extra_body.
    extra_body={"translation_options": {"source_lang": "auto", "target_lang": "English"}},
)
# Impor dependensi...
response = dashscope.Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-mt-flash",  # Pilih model
    messages=[{"role": "user", "content": "No me reí después de ver este video"}],  # messages: 'role' adalah 'user' dan 'content' adalah teks yang akan diterjemahkan.
    translation_options={"source_lang": "auto", "target_lang": "English"},  # Konfigurasikan opsi terjemahan.
    result_format="message"
)
import os
from openai import OpenAI
client = OpenAI(
    # Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-mt-flash",
    # Parameter messages harus berisi tepat satu pesan dengan role 'user', dan content-nya adalah teks yang akan diterjemahkan.
    messages=[
        {
            "role": "user",
            "content": "No me reí después de ver este video"
        }
    ],
    # Karena translation_options bukan parameter standar OpenAI, Anda harus melewatkan parameter ini menggunakan parameter extra_body.
    extra_body={
        # Konfigurasikan opsi terjemahan.
        "translation_options": {
            "source_lang": "auto",
            "target_lang": "English"
        }
    },
)
import os
import dashscope
# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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",
    # Parameter messages harus berisi tepat satu pesan dengan role "user", dan content-nya adalah teks yang akan diterjemahkan.
    messages=[
        {
            "role": "user",
            "content": "No me reí después de ver este video"
        }
    ],
    # Konfigurasikan opsi terjemahan.
    translation_options={
        "source_lang": "auto",
        "target_lang": "English",
    },
    result_format="message"
)
print(response.output.choices[0].message.content)

Gunakan parameter translation_options untuk mengakses fitur terjemahan lanjutan seperti intervensi istilah, memori terjemahan, dan prompting domain.

Batasan
  • Hanya terjemahan satu arah: Qwen-MT dirancang khusus untuk terjemahan dan tidak mendukung percakapan multi-putaran.
  • Pesan sistem tidak didukung: Anda tidak dapat mengatur perilaku global melalui pesan dengan role system. Sebagai gantinya, konfigurasikan perilaku terjemahan dalam parameter translation_options.

Pemilihan model

  • Untuk skenario umum, pilih qwen-mt-flash. Model ini menawarkan keseimbangan terbaik antara kualitas, kecepatan, dan biaya, serta mendukung keluaran streaming inkremental.
  • Untuk kualitas terjemahan tertinggi di bidang profesional, pilih qwen-mt-plus.
  • Untuk kecepatan respons tercepat dalam skenario sederhana dan real-time, pilih qwen-mt-lite.

Tabel berikut membandingkan model-model yang tersedia.

Model

Skenario

Hasil

Kecepatan

Biaya

Bahasa yang didukung

Streaming inkremental

qwen-mt-plus

Memberikan terjemahan berkualitas tinggi untuk skenario seperti bidang profesional, dokumen formal, makalah akademis, dan laporan teknis

Terbaik

Standar

Tinggi

92

Tidak didukung

qwen-mt-flash

Disarankan untuk penggunaan umum. Cocok untuk konten website dan aplikasi, deskripsi produk, komunikasi sehari-hari, dan posting blog

Baik

Cepat

Rendah

92

Didukung

qwen-mt-turbo

Model ini tidak akan diperbarui di masa depan. Gunakan flash sebagai gantinya.

Cukup

Cepat

Rendah

92

Tidak didukung

qwen-mt-lite

Skenario sederhana yang sensitif terhadap latensi seperti obrolan real-time dan terjemahan komentar langsung

Dasar

Paling cepat

Paling rendah

31

Didukung

Periksa batas jendela konteks dan harga di Konsol. Untuk batas permintaan konkuren, lihat Model terjemahan Qwen.

Mulai

Bagian ini menjelaskan contoh sederhana: menerjemahkan "No me reí después de ver este video" ke dalam bahasa Inggris.

Dapatkan Kunci API dan ekspor Kunci API sebagai variabel lingkungan. Jika Anda menggunakan SDK OpenAI atau SDK DashScope untuk melakukan panggilan, instal SDK.

Kompatibel dengan OpenAI

Permintaan contoh
import os
from openai import OpenAI

client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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)
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

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"
      }
}'
Respons contoh
I didn't laugh after watching this video.

DashScope

Permintaan contoh

PentingSDK Java DashScope harus versi 2.20.6 atau lebih baru.

import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",  # Contoh ini menggunakan qwen-mt-turbo. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan.
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// Diperlukan SDK DashScope versi 2.20.6 atau lebih baru.
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 {
        // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
        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()
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: .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);
        }
    }
}
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'
Respons contoh
I didn't laugh after watching this video.

Keluaran streaming

Keluaran streaming mengirimkan konten terjemahan secara bertahap, sehingga mengurangi latensi yang dirasakan. Saat ini, qwen-mt-flash dan qwen-mt-lite mendukung streaming inkremental, di mana setiap respons hanya berisi konten yang baru dihasilkan. Aktifkan fitur ini dengan parameter incremental_output. Sementara itu, qwen-mt-plus dan qwen-mt-turbo hanya mendukung streaming non-inkremental, di mana setiap respons mengembalikan seluruh terjemahan hingga titik tersebut. Untuk informasi lebih lanjut, lihat Keluaran streaming.

Kompatibel dengan OpenAI

Permintaan contoh
import os
from openai import OpenAI

client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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)
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

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"
      }
}'
Respons contoh
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

Permintaan contoh
import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-flash",  # Contoh ini menggunakan qwen-mt-turbo. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan.
    messages=messages,
    result_format='message',
    stream=True,
    # Untuk mendapatkan keluaran inkremental, atur incremental_output ke True. Ini direkomendasikan. Saat ini, hanya qwen-mt-flash dan qwen-mt-lite yang mendukung fitur ini.
    incremental_output=True,
    translation_options=translation_options
)
for chunk in response:
    print(chunk.output.choices[0].message.content, end="", flush=True)
// SDK DashScope harus versi 2.20.6 atau lebih baru.
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)
                // Aktifkan keluaran inkremental. Fitur ini hanya didukung oleh qwen-mt-flash dan qwen-mt-lite.
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void main(String[] args) {
        try {
            // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
            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);
    }
}
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
  "model": "qwen-mt-flash",
  "input": {
    "messages": [
      {
        "content": "No me reí después de ver este video",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    },
    "incremental_output": true
  }
}'
Respons contoh
I didn't laugh after watching this video.

qwen-mt-plus dan qwen-mt-turbo tidak mendukung keluaran streaming inkremental.

Tingkatkan kualitas terjemahan

Terjemahan dasar bekerja dengan baik untuk kasus penggunaan sehari-hari seperti komunikasi santai. Namun, untuk tugas terjemahan profesional atau bernilai tinggi, Anda mungkin menghadapi tantangan spesifik:

  • Istilah tidak konsisten: Nama produk atau istilah khusus industri diterjemahkan salah atau tidak konsisten di berbagai bagian teks.
  • Gaya tidak sesuai: Teks terjemahan tidak sesuai dengan nada atau konvensi yang diharapkan dalam domain tertentu, seperti konten hukum atau pemasaran.

Qwen-MT menyediakan tiga fitur untuk mengatasi tantangan ini: intervensi istilah, memori terjemahan, dan prompting domain.

Intervensi istilah

Sediakan glosarium dalam field terms untuk memastikan bahwa nama merek, nama produk, atau istilah teknis diterjemahkan secara konsisten setiap kali.

Untuk mendefinisikan dan mengirimkan glosarium Anda:

  1. Definisikan istilah

    Buat array JSON dan tetapkan ke field terms. Setiap objek dalam array memetakan istilah sumber ke terjemahannya yang ditentukan:

{
    "source": "term",
    "target": "pre-translated term"
}
  1. Kirimkan istilah

    Kirimkan parameter translation_options dengan array terms Anda sertakan.

Kompatibel dengan OpenAI

Permintaan contoh
import os
from openai import OpenAI

client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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."
    }
]

# --- Permintaan pertama: tanpa parameter terms ---
print("--- [Hasil terjemahan tanpa terms] ---")
translation_options_without_terms = {
    "source_lang": "auto",
    "target_lang": "English"
}

completion_without_terms = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options_without_terms
    }
)
print(completion_without_terms.choices[0].message.content)

print("\n" + "="*50 + "\n") # Pemisah untuk perbandingan

# --- Permintaan kedua: dengan parameter terms ---
print("--- [Hasil terjemahan dengan terms] ---")
translation_options_with_terms = {
    "source_lang": "auto",
    "target_lang": "English",
    "terms": [
        {
            "source": "biosensor",
            "target": "biological sensor"
        },
        {
            "source": "estado de salud del cuerpo",
            "target": "health status of the body"
        }
    ]
}

completion_with_terms = client.chat.completions.create(
    model="qwen-mt-turbo",
    messages=messages,
    extra_body={
        "translation_options": translation_options_with_terms
    }
)
print(completion_with_terms.choices[0].message.content)
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "messages": [
    {
      "role": "user",
      "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa."
    }
  ],
  "translation_options": {
    "source_lang": "auto",
    "target_lang": "English",
    "terms": [
      {
        "source": "biosensor",
        "target": "biological sensor"
      },
      {
        "source": "estado de salud del cuerpo",
        "target": "health status of the body"
      }
    ]
  }
}'
Respons contoh

Setelah Anda menambahkan glosarium, keluaran terjemahan mencerminkan istilah yang Anda tentukan: "biological sensor" dan "health status of the body".

--- [Hasil terjemahan tanpa istilah] ---
Rangkaian biosensor ini menggunakan grafena, sebuah material baru, yang substansi targetnya adalah unsur-unsur kimia. "Indra penciuman"-nya yang sensitif memungkinkannya untuk mencerminkan kondisi kesehatan seseorang secara lebih mendalam dan akurat.

==================================================

--- [Hasil terjemahan dengan istilah] ---
Sensor biologis ini menggunakan material baru yang disebut grafena. Targetnya adalah unsur-unsur kimia, dan "indra penciuman"-nya yang sensitif memungkinkannya untuk mencerminkan status kesehatan tubuh secara lebih mendalam dan akurat.

DashScope

Permintaan contoh
import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",  # Contoh ini menggunakan qwen-mt-turbo. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan.
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// SDK DashScope harus versi 2.20.6 atau lebih baru.
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 {
        // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
        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);
    }
}
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "Este conjunto de biosensores utiliza grafeno, un material novedoso. Su objetivo son los elementos químicos. Su agudo «sentido del olfato» le permite reflejar el estado de salud del cuerpo de forma más profunda y precisa.",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English",
      "terms": [
        {
          "source": "biosensor",
          "target": "biological sensor"
        },
        {
          "source": "estado de salud del cuerpo",
          "target": "health status of the body"
        }
      ]
    }
  }
}'
Respons contoh
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.

Memori terjemahan

Ketika Anda ingin model mengikuti gaya terjemahan atau pola kalimat tertentu, berikan pasangan kalimat sumber-target sebagai contoh dalam field tm_list. Model belajar dari gaya pasangan referensi ini dan menerapkannya pada terjemahan saat ini. Fitur ini berguna untuk menjaga konsistensi di seluruh kumpulan dokumentasi besar atau saat menyesuaikan dengan konvensi penulisan yang telah ditetapkan oleh organisasi.

  1. Definisikan memori terjemahan

    Buat array JSON bernama tm_list. Setiap objek memasangkan kalimat sumber dengan terjemahan referensinya:

{
    "source": "source statement",
    "target": "translated statement"
}
  1. Teruskan memori terjemahan

    Sertakan parameter translation_options dengan array memori terjemahan Anda.

Contoh berikut menunjukkan memori terjemahan dalam praktik.

Kompatibel dengan OpenAI

Permintaan contoh
import os
from openai import OpenAI

client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # base_url bervariasi berdasarkan wilayah. Perbarui berdasarkan wilayah yang Anda gunakan.
    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)
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

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

DashScope

Permintaan contoh
import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-turbo",  # Contoh ini menggunakan qwen-mt-turbo. Anda dapat menggantinya dengan nama model lain sesuai kebutuhan.
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)
// SDK DashScope harus versi 2.20.6 atau lebih baru.
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 {
        // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
        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);
    }
}
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

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

Prompting domain

Kirimkan prompt domain dalam translation_options untuk menyesuaikan gaya terjemahan sesuai bidang tertentu. Misalnya, konten hukum atau pemerintahan memerlukan bahasa formal, sedangkan posting media sosial lebih cocok dengan nada percakapan.

PentingPrompt domain saat ini hanya mendukung bahasa Inggris.

Kompatibel dengan OpenAI

Permintaan contoh
import os
from openai import OpenAI

client = OpenAI(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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."
    }
]

# --- Permintaan pertama: tanpa parameter domains ---
print("--- [Hasil terjemahan tanpa 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") # Pemisah untuk perbandingan

# --- Permintaan kedua: dengan parameter domains ---
print("--- [Hasil terjemahan dengan 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)
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-turbo",
  "messages": [
    {
      "role": "user",
      "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT."
    }
  ],
  "translation_options": {
    "source_lang": "auto",
    "target_lang": "English",
    "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
  }
}'
Respons contoh
--- [Hasil terjemahan tanpa domain] ---
Pernyataan SELECT kedua mengembalikan angka yang menunjukkan jumlah baris yang akan dikembalikan oleh pernyataan SELECT pertama tanpa klausul LIMIT.

==================================================

--- [Hasil terjemahan dengan domain] ---
Pernyataan SELECT kedua mengembalikan angka yang menunjukkan jumlah baris yang akan dikembalikan oleh pernyataan SELECT pertama jika tidak menyertakan klausul LIMIT.

DashScope

Permintaan contoh
import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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)
// SDK DashScope harus versi 2.20.6 atau lebih baru.
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 {
        // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
        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"))
                // Catatan: qwen-mt-lite tidak mendukung prompting domain
                .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);
    }
}
# ======= Penting =======
# URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
# === Hapus komentar ini sebelum eksekusi ====

curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-turbo",
  "input": {
    "messages": [
      {
        "content": "La segunda instrucción SELECT devuelve un número que indica la cantidad de filas que habría devuelto la primera instrucción SELECT si no se hubiera utilizado la cláusula LIMIT.",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English",
      "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
  }
}'
Respons contoh
The second SELECT statement returns a number that indicates how many rows were returned by the first SELECT statement without a LIMIT clause.

Prompt kustom

Gunakan prompt kustom dengan Qwen-MT untuk mengontrol detail seperti bahasa target, nada, atau domain. Parameter translation_options dan prompt kustom dapat dikirimkan bersamaan, tetapi ketika keduanya diatur secara bersamaan, pengaturan dalam translation_options (seperti target_lang, source_lang, dan sebagainya) memiliki prioritas lebih tinggi daripada pengaturan yang sesuai dalam prompt kustom dan akan menggantikan spesifikasi bahasa atau gaya dalam prompt kustom.

Untuk hasil terjemahan terbaik, gunakan translation_options untuk mengonfigurasi pengaturan terjemahan.

Contoh berikut menunjukkan terjemahan hukum dari Spanyol ke Inggris menggunakan prompt terperinci:

Kompatibel dengan OpenAI

import os
from openai import OpenAI

client = OpenAI(
    # Jika variabel lingkungan belum dikonfigurasi, ganti baris berikut dengan Kunci API Alibaba Cloud Model Studio Anda: api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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. Siapkan teks hukum yang akan diterjemahkan ---
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. Buat messages ---
messages = [{"role": "user", "content": final_prompt}]

# --- 4. Lakukan permintaan API ---
completion = client.chat.completions.create(model="qwen-mt-plus", messages=messages)

# --- 5. Cetak hasil terjemahan model ---
translation_result = completion.choices[0].message.content
print(translation_result)
import OpenAI from 'openai';

const client = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
    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();
Respons contoh
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

Permintaan contoh
import os
import dashscope

# URL dasar berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
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. Siapkan teks hukum untuk diterjemahkan ---
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. Buat messages ---
messages = [
    {
        "role": "user",
        "content": final_prompt
    }
]

response = dashscope.Generation.call(
    # Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: 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)
// SDK DashScope harus versi 2.20.6 atau lebih baru.
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 {
        // URL berbeda-beda tergantung wilayah. Perbarui sesuai wilayah yang Anda gunakan.
        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()
                // Jika Anda belum mengonfigurasi variabel lingkungan, ganti baris berikut dengan Kunci API Model Studio Anda: .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();
        }
        }
}
Respons contoh
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.

Mulai produksi

  • Kontrol jumlah token input

    Model Qwen-MT menerima maksimal 8.192 token input. Untuk konten yang lebih panjang, gunakan strategi berikut agar tetap dalam batas ini:

    • Terjemahkan per segmen: Pecah teks panjang menjadi potongan-potongan yang mudah dikelola pada batas semantik alami — seperti paragraf atau kalimat lengkap — daripada membagi berdasarkan jumlah karakter. Hal ini menjaga koherensi konteks dan menghasilkan terjemahan yang lebih akurat.
    • Berikan hanya referensi yang paling relevan: Istilah, entri memori terjemahan, dan prompt domain semuanya mengonsumsi token input. Sertakan hanya referensi yang secara langsung relevan dengan teks yang sedang diterjemahkan. Hindari melewatkan daftar referensi generik yang besar.
  • Tentukansource_langberdasarkan skenario

    • Ketika bahasa sumber tidak pasti — misalnya, dalam skenario obrolan multibahasa — atur source_lang ke auto. Model akan mengidentifikasi bahasa secara otomatis.
    • Ketika bahasa sumber diketahui dan akurasi sangat penting — seperti untuk dokumentasi teknis atau manual operasi — selalu tentukan source_lang secara eksplisit. Hal ini meningkatkan akurasi terjemahan.

Bahasa yang didukung

Saat mengirim permintaan, gunakan Nama Bahasa Inggris atau Kode dari tabel di bawah ini.

Jika Anda tidak yakin dengan bahasa sumber, Anda dapat mengatur parameter source_lang ke auto untuk deteksi otomatis.

Bahasa yang didukung oleh qwen-mt-plus/flash/turbo (92)

Bahasa

English Name

Kode

Inggris

English

en

Tiongkok Sederhana

Chinese

zh

Tiongkok Tradisional

Traditional Chinese

zh_tw

Rusia

Russian

ru

Jepang

Japanese

ja

Bahasa Korea

Korean

ko

Spanyol

Spanish

es

Prancis

French

fr

Portugis

Portuguese

pt

Jerman

German

de

Bahasa Italia

Italian

it

Thai

Thai

th

Bahasa Vietnam

Vietnamese

vi

Bahasa Indonesia

Indonesian

id

Melayu

Malay

ms

Arab

Arabic

ar

Hindi

Hindi

hi

Ibrani

Hebrew

he

Bahasa Myanmar

Burmese

my

Tamil

Tamil

ta

Urdu

Urdu

ur

Bengali

Bengali

bn

Polandia

Polish

pl

Belanda

Dutch

nl

Rumania

Romanian

ro

Turki

Turkish

tr

Khmer

Khmer

km

Lao

Lao

lo

Kanton

Cantonese

yue

Ceko

Czech

cs

Yunani

Greek

el

Swedia

Swedish

sv

Hongaria

Hungarian

hu

Denmark

Danish

da

Finlandia

Finnish

fi

Ukraina

Ukrainian

uk

Bulgaria

Bulgarian

bg

Serbia

Serbian

sr

Telugu

Telugu

te

Afrikaans

Afrikaans

af

Armenia

Armenian

hy

Bahasa Assam

Assamese

as

Asturia

Asturian

ast

Basque

Basque

eu

Belarusia

Belarusian

be

Bahasa Bosnia

Bosnian

bs

Katalan

Catalan

ca

Cebuano

Cebuano

ceb

Kroasia

Croatian

hr

Arab Mesir

Egyptian Arabic

arz

Bahasa Esti

Estonian

et

Galisia

Galician

gl

Georgia

Georgian

ka

Gujarati

Gujarati

gu

Islandia

Icelandic

is

Jawa

Javanese

jv

Kannada

Kannada

kn

Kazakh

Kazakh

kk

Latvia

Latvian

lv

Lituania

Lithuanian

lt

Luksemburg

Luxembourgish

lb

Makedonia

Macedonian

mk

Maithili

Maithili

mai

Malta

Maltese

mt

Marathi

Marathi

mr

Arab Mesopotamia

Mesopotamian Arabic

acm

Arab Maroko

Moroccan Arabic

ary

Arab Najdi

Najdi Arabic

ars

Nepali

Nepali

ne

Azerbaijani Utara

North Azerbaijani

az

Arab Levant Utara

North Levantine Arabic

apc

Uzbek Utara

Northern Uzbek

uz

Bokmål Norwegia

Norwegian Bokmål

nb

Nynorsk Norwegia

Norwegian Nynorsk

nn

Occitan

Occitan

oc

Odia

Odia

or

Pangasinan

Pangasinan

pag

Sisilia

Sicilian

scn

Sindhi

Sindhi

sd

Sinhala

Sinhala

si

Slovak

Slovak

sk

Slovenia

Slovenian

sl

Arab Levant Selatan

South Levantine Arabic

ajp

Swahili

Swahili

sw

Tagalog

Tagalog

tl

Arab Ta’izzi-Adeni

Ta’izzi-Adeni Arabic

acq

Albania Tosk

Tosk Albanian

sq

Arab Tunisia

Tunisian Arabic

aeb

Venetian

Venetian

vec

Valaisan

Waray

war

Bahasa Wales

Welsh

cy

Persia Barat

Western Persian

fa

Bahasa yang didukung oleh qwen-mt-lite (31)

Bahasa

Nama Bahasa Inggris

Kode

Inggris

English

en

Tionghoa Sederhana

Chinese

zh

Tiongkok Tradisional

Traditional Chinese

zh_tw

Rusia

Russian

ru

Jepang

Japanese

ja

Bahasa Korea

Korean

ko

Spanyol

Spanish

es

Prancis

French

fr

Portugis

Portuguese

pt

Jerman

German

de

Italia

Italian

it

Thai

Thai

th

Bahasa Vietnam

Vietnamese

vi

Bahasa Indonesia

Indonesian

id

Melayu

Malay

ms

Arab

Arabic

ar

Hindi

Hindi

hi

Ibrani

Hebrew

he

Urdu

Urdu

ur

Bengali

Bengali

bn

Polandia

Polish

pl

Belanda

Dutch

nl

Turki

Turkish

tr

Khmer

Khmer

km

Ceko

Czech

cs

Swedia

Swedish

sv

Hongaria

Hungarian

hu

Denmark

Danish

da

Finlandia

Finnish

fi

Tagalog

Tagalog

tl

Persia

Persian

fa

Referensi API

Untuk spesifikasi parameter input dan output yang lebih rinci, lihat Qwen-MT.