全部產品
Search
文件中心

Alibaba Cloud Model Studio:Qwen-MT API 參考

更新時間:Dec 17, 2025

本文介紹通過 OpenAI 相容介面 或 DashScope API 調用 Qwen-MT 模型的輸入與輸出參數。

相關文檔:翻譯能力(Qwen-MT)

OpenAI 相容

新加坡地區

SDK 調用配置的base_url為:https://dashscope-intl.aliyuncs.com/compatible-mode/v1

HTTP 調用配置的endpointPOST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

北京地區

SDK 調用配置的base_url為:https://dashscope.aliyuncs.com/compatible-mode/v1

HTTP 調用配置的endpointPOST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions

您需要已擷取與配置 API Key配置API Key到環境變數(準備下線,併入配置 API Key)。若通過OpenAI SDK進行調用,需要安裝SDK

請求體

基礎使用

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "我看到這個視頻後沒有笑"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English"
}

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

Node.js

// 需要 Node.js v18+,需在 ES Module 環境下運行
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下是新加坡地區base_url,如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen-mt-plus", 
    messages: [
        { role: "user", content: "我看到這個視頻後沒有笑" }
    ],
    translation_options: {
        source_lang: "Chinese",
        target_lang: "English"
    }
});
console.log(JSON.stringify(completion));

curl

# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。
# 以下是新加坡地區endpoint,如果使用北京地區的模型,需要將endpoint替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-mt-plus",
    "messages": [{"role": "user", "content": "看完這個視頻我沒有笑"}],
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
      }
}'

術語幹預

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
        {
            "source": "生物特徵辨識感應器",
            "target": "biological sensor"
        },
        {
            "source": "石墨烯",
            "target": "graphene"
        },
        {
            "source": "化學元素",
            "target": "chemical elements"
        },
        {
            "source": "身體健康情況",
            "target": "health status of the body"
        }
    ]
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  # 此處以qwen-mt-plus為例,可按需更換模型名稱
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// 需要 Node.js v18+,需在 ES Module 環境下運行
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下是新加坡地區base_url,如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen-mt-plus",
    messages: [
        { role: "user", content: "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。" }
    ],
    translation_options: {
        source_lang: "Chinese",
        target_lang: "English",
        terms: [
            {
                "source": "生物特徵辨識感應器",
                "target": "biological sensor"
            },
            {
                "source": "石墨烯",
                "target": "graphene"
            },
            {
                "source": "化學元素",
                "target": "chemical elements"
            },
            {
                "source": "身體健康情況",
                "target": "health status of the body"
            }
        ]
    }
});
console.log(JSON.stringify(completion));

curl

# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。
# 以下是新加坡地區endpoint,如果使用北京地區的模型,需要將endpoint替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-plus",
  "messages": [
    {
      "role": "user",
      "content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
      {
        "source": "生物特徵辨識感應器",
        "target": "biological sensor"
      },
      {
        "source": "石墨烯",
        "target": "graphene"
      },
      {
        "source": "化學元素",
        "target": "chemical elements"
      },
      {
        "source": "身體健康情況",
        "target": "health status of the body"
      }
    ]
  }
}'

翻譯記憶

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "通過如下命令可以看出安裝thrift的版本資訊;"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "您可以通過如下方式查看叢集的核心版本資訊:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;",
            "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
        },
        {
            "source": "您可以通過PyPI來安裝SDK,安裝命令如下:",
            "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
        }
    ]
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  # 此處以qwen-mt-plus為例,可按需更換模型名稱
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// 需要 Node.js v18+,需在 ES Module 環境下運行
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下是新加坡地區base_url,如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    model: "qwen-mt-plus",
    messages: [
        { role: "user", content: "通過如下命令可以看出安裝thrift的版本資訊;" }
    ],
    translation_options: {
        source_lang: "Chinese",
        target_lang: "English",
        tm_list: [
            {
                "source": "您可以通過如下方式查看叢集的核心版本資訊:",
                "target": "You can use one of the following methods to query the engine version of a cluster:"
            },
            {
                "source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;",
                "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
            },
            {
                "source": "您可以通過PyPI來安裝SDK,安裝命令如下:",
                "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
            }
        ]
    }
});
console.log(JSON.stringify(completion));

curl

# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。
# 以下是新加坡地區endpoint,如果使用北京地區的模型,需要將endpoint替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-plus",
  "messages": [
    {
      "role": "user",
      "content": "通過如下命令可以看出安裝thrift的版本資訊;"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list":[
          {"source": "您可以通過如下方式查看叢集的核心版本資訊:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
          {"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
          {"source": "您可以通過PyPI來安裝SDK,安裝命令如下:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
    ]
  }
}'

領域提示

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
messages = [
    {
        "role": "user",
        "content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}

completion = client.chat.completions.create(
    model="qwen-mt-plus",  # 注意,qwen-mt-lite模型不支援領域提示功能
    messages=messages,
    extra_body={
        "translation_options": translation_options
    }
)
print(completion.choices[0].message.content)

Node.js

// 需要 Node.js v18+,需在 ES Module 環境下運行
import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:apiKey: "sk-xxx",
        apiKey: process.env.DASHSCOPE_API_KEY,
        // 以下是新加坡地區base_url,如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
        baseURL: "https://dashscope-intl.aliyuncs.com/compatible-mode/v1"
    }
);
const completion = await openai.chat.completions.create({
    // 注意,qwen-mt-lite模型不支援領域提示功能
    model: "qwen-mt-plus",
    messages: [
        { role: "user", content: "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。" }
    ],
    translation_options: {
        source_lang: "Chinese",
        target_lang: "English",
        domains: "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
    }
});
console.log(JSON.stringify(completion));

curl

# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。
# 以下是新加坡地區endpoint,如果使用北京地區的模型,需要將endpoint替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-plus",
  "messages": [
    {
      "role": "user",
      "content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
    }
  ],
  "translation_options": {
    "source_lang": "Chinese",
    "target_lang": "English",
    "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
  }
}'

model string (必選)

模型名稱。支援的模型:qwen-mt-plus、qwen-mt-flash、qwen-mt-lite、qwen-mt-turbo。

messages array (必選)

訊息數組,用於向大模型傳遞上下文。僅支援傳入 User Message。

訊息類型

User Message object (必選)

使用者訊息,用於傳遞待翻譯的句子。

屬性

content string(必選)

待翻譯的句子。

role string (必選)

使用者訊息的角色,必須設為user

stream boolean (可選) 預設值為 false

是否以流式方式輸出回複。

可選值:

  • false:等待模型產生完整回複後一次性返回。

  • true:模型邊產生邊返回資料區塊。用戶端需逐塊讀取,以還原完整回複。

說明

當前僅qwen-mt-flash、qwen-mt-lite模型支援以增量形式返回資料,每次返回僅包含新產生的內容。qwen-mt-plus和qwen-mt-turbo模型以非增量形式返回資料,每次返回當前已經產生的整個序列,暫時無法修改。如:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

stream_options object (可選)

流式輸出的配置項,僅在 streamtrue 時生效。

屬性

include_usage boolean (可選)預設值為 false

是否在最後一個資料區塊包含Token消耗資訊。

可選值:

  • true:包含;

  • false:不包含。

max_tokens integer (可選)

用於限制模型輸出的最大 Token 數。若產生內容超過此值,響應將被截斷。

預設值與最大值均為模型的最大輸出長度,請參見模型選型

seed integer (可選)

隨機數種子。用於確保在相同輸入和參數下產生結果可複現。若調用時傳入相同的 seed 且其他參數不變,模型將儘可能返回相同結果。

取值範圍:[0,231−1]

temperature float (可選) 預設值為0.65

採樣溫度,控制模型產生文本的多樣性。

temperature越高,產生的文本更多樣,反之,產生的文本更確定。

取值範圍: [0, 2)

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。

top_p float (可選)預設值為0.8

核採樣的機率閾值,控制模型產生文本的多樣性。

top_p越高,產生的文本更多樣。反之,產生的文本更確定。

取值範圍:(0,1.0]

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。

top_k integer (可選)預設值為1

產生過程中採樣候選集的大小。例如,取值為50時,僅將單次產生中得分最高的50個Token組成隨機採樣的候選集。取值越大,產生的隨機性越高;取值越小,產生的確定性越高。取值為None或當top_k大於100時,表示不啟用top_k策略,此時僅有top_p策略生效。

取值需要大於或等於0。

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中,配置方式為:extra_body={"top_k": xxx};通過 Node.js SDK 或 HTTP 方式調用時,請作為頂層參數傳遞。

repetition_penalty float (可選)預設值為1.0

模型產生時連續序列中的重複度。提高repetition_penalty時可以降低模型產生的重複度,1.0表示不做懲罰。沒有嚴格的取值範圍,只要大於0即可。

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中,配置方式為:extra_body={"repetition_penalty": xxx};通過 Node.js SDK 或 HTTP 方式調用時,請作為頂層參數傳遞。

translation_options object (必選)

需配置的翻譯參數。

屬性

source_lang string (必選)

源語言的英文全稱,詳情請參見支援的語言。若設為auto,模型會自動識別輸入的語種。

target_lang string (必選)

目標語言的英文全稱,詳情請參見支援的語言

terms arrays (可選)

使用術語幹預功能時需設定的術語數組。

屬性

source string (必選)

源語言的術語。

target string (必選)

目標語言的術語。

tm_list arrays (可選)

使用翻譯記憶功能時需設定的翻譯記憶數組。

屬性

source string (必選)

源語言的語句。

target string (必選)

目標語言的語句。

domains string (可選)

使用領域提示功能時需設定的領域提示句。

領域提示句暫時只支援英文。
qwen-mt-lite模型不支援領域提示功能。

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中,配置方式為:extra_body={"translation_options": xxx};通過 Node.js SDK 或 HTTP 方式調用時,請作為頂層參數傳遞。

chat響應對象(非流式輸出)

{
  "id": "chatcmpl-999a5d8a-f646-4039-968a-167743ae0f22",
  "choices": [
    {
      "finish_reason": "stop",
      "index": 0,
      "logprobs": null,
      "message": {
        "content": "I didn't laugh after watching this video.",
        "refusal": null,
        "role": "assistant",
        "annotations": null,
        "audio": null,
        "function_call": null,
        "tool_calls": null
      }
    }
  ],
  "created": 1762346157,
  "model": "qwen-mt-plus",
  "object": "chat.completion",
  "service_tier": null,
  "system_fingerprint": null,
  "usage": {
    "completion_tokens": 9,
    "prompt_tokens": 53,
    "total_tokens": 62,
    "completion_tokens_details": null,
    "prompt_tokens_details": null
  }
}

id string

本次請求的唯一識別碼。

choices array

模型產生內容的數組。

屬性

finish_reason string

模型停止產生的原因。

有兩種情況:

  • 自然停止輸出時為stop

  • 產生長度過長而結束為length

index integer

當前對象在choices數組中的索引。

message object

模型輸出的訊息。

屬性

content string

模型翻譯結果。

refusal string

該參數當前固定為null

role string

訊息的角色,固定為assistant

audio object

該參數當前固定為null

function_call object

該參數當前固定為null

tool_calls array

該參數當前固定為null

created integer

本次請求被建立時的時間戳記。

model string

本次請求使用的模型。

object string

始終為chat.completion

service_tier string

該參數當前固定為null

system_fingerprint string

該參數當前固定為null

usage object

本次請求的 Token 消耗資訊。

屬性

completion_tokens integer

模型輸出的 Token 數。

prompt_tokens integer

輸入的 Token 數。

total_tokens integer

消耗的總 Token 數,為prompt_tokenscompletion_tokens的總和。

completion_tokens_details object

該參數當前固定為null

prompt_tokens_details object

該參數當前固定為null

chat響應chunk對象(流式輸出)

增量輸出

{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": "assistant", "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "I", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " didn", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "'t", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " laugh", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " after", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " watching", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " this", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": " video", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": ".", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": null, "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": "stop", "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [{"delta": {"content": "", "function_call": null, "refusal": null, "role": null, "tool_calls": null}, "finish_reason": "stop", "index": 0, "logprobs": null}], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": null}
{"id": "chatcmpl-d8aa6596-b366-4ed0-9f6d-2e89247f554e", "choices": [], "created": 1762504029, "model": "qwen-mt-flash", "object": "chat.completion.chunk", "service_tier": null, "system_fingerprint": null, "usage": {"completion_tokens": 9, "prompt_tokens": 56, "total_tokens": 65, "completion_tokens_details": null, "prompt_tokens_details": null}}

非增量輸出

{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[{"delta":{"content":"I didn’t laugh after watching this video.","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-478e183e-cbdc-4ea0-aeae-4c2ba1d03e4d","choices":[],"created":1762346453,"model":"qwen-mt-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":9,"prompt_tokens":56,"total_tokens":65,"completion_tokens_details":null,"prompt_tokens_details":null}}

id string

本次調用的唯一識別碼。每個chunk對象有相同的 id。

choices array

模型產生內容的數組。若設定include_usage參數為true,則在最後一個chunk中為空白。

屬性

delta object

流式返回的輸出內容。

屬性

content string

翻譯結果,qwen-mt-flash和qwen-mt-lite為增量式更新,qwen-mt-plus和qwen-mt-turbo為非增量式更新。

function_call object

該參數當前固定為null

refusal object

該參數當前固定為null

role string

訊息對象的角色,只在第一個chunk中有值。

finish_reason string

模型停止產生的原因。有三種情況:

  • 自然停止輸出時為stop

  • 產生未結束時為null

  • 產生長度過長而結束為length

index integer

當前響應在choices數組中的索引。

created integer

本次請求被建立時的時間戳記。每個chunk有相同的時間戳記。

model string

本次請求使用的模型。

object string

始終為chat.completion.chunk

service_tier string

該參數當前固定為null

system_fingerprintstring

該參數當前固定為null

usage object

本次請求消耗的Token。只在include_usagetrue時,在最後一個chunk返回。

屬性

completion_tokens integer

模型輸出的 Token 數。

prompt_tokens integer

輸入 Token 數。

total_tokens integer

總 Token 數,為prompt_tokenscompletion_tokens的總和。

completion_tokens_details object

該參數當前固定為null

prompt_tokens_details object

該參數當前固定為null

DashScope

新加坡地區

HTTP 調用配置的endpointPOST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK調用配置的base_url

Python代碼

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

Java代碼

  • 方式一:

    import com.alibaba.dashscope.protocol.Protocol;
    Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
  • 方式二:

    import com.alibaba.dashscope.utils.Constants;
    Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";

北京地區

HTTP 調用配置的endpointPOST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

SDK 調用無需配置 base_url

您需要已擷取與配置 API Key配置API Key到環境變數(準備下線,併入配置 API Key)。若通過DashScope SDK進行調用,需要安裝DashScope SDK

請求體

基礎使用

Python

import os
import dashscope

# 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "我看到這個視頻後沒有笑"
    }
]
translation_options = {
    "source_lang": "auto",
    "target_lang": "English",
}
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # 此處以qwen-mt-plus為例,可按需更換模型名稱
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 版本需要不低於 2.20.6
import java.lang.System;
import java.util.Collections;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("我看到這個視頻後沒有笑")
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-mt-plus")
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("錯誤資訊:"+e.getMessage());
            e.printStackTrace();
        } finally {
            System.exit(0);
        }
    }
}

curl

# ======= 重要提示 =======
# 如果使用北京地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 執行時請刪除該注釋 ====

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
  "model": "qwen-mt-plus",
  "input": {
    "messages": [
      {
        "content": "我看到這個視頻後沒有笑",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "auto",
      "target_lang": "English"
    }
  }
}'

術語幹預

Python

import os
import dashscope

# 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "terms": [
        {
            "source": "生物特徵辨識感應器",
            "target": "biological sensor"
        },
        {
            "source": "石墨烯",
            "target": "graphene"
        },
        {
            "source": "化學元素",
            "target": "chemical elements"
        },
        {
            "source": "身體健康情況",
            "target": "health status of the body"
        }
    ]
}
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # 此處以qwen-mt-plus為例,可按需更換模型名稱
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 版本需要不低於 2.20.6
import java.lang.System;
import java.util.Collections;
import java.util.Arrays;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.aigc.generation.TranslationOptions.Term;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。")
                .build();
        Term term1 = Term.builder()
                .source("生物特徵辨識感應器")
                .target("biological sensor")
                .build();
        Term term2 = Term.builder()
                .source("身體健康情況")
                .target("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("錯誤資訊:"+e.getMessage());
        }
        System.exit(0);
    }
}

curl

# ======= 重要提示 =======
# 如果使用北京地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 執行時請刪除該注釋 ====

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-plus",
  "input": {
    "messages": [
      {
        "content": "而這套生物特徵辨識感應器運用了石墨烯這種新型材料,它的目標物是化學元素,敏銳的“嗅覺”讓它能更深度、準確地體現身體健康情況。",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English",
      "terms": [
        {
          "source": "生物特徵辨識感應器",
          "target": "biological sensor"
        },
        {
          "source": "身體健康情況",
          "target": "health status of the body"
        }
      ]
  }
}'

翻譯記憶

Python

import os
import dashscope

# 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "通過如下命令可以看出安裝thrift的版本資訊;"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "tm_list": [
        {
            "source": "您可以通過如下方式查看叢集的核心版本資訊:",
            "target": "You can use one of the following methods to query the engine version of a cluster:"
        },
        {
            "source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;",
            "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."
        },
        {
            "source": "您可以通過PyPI來安裝SDK,安裝命令如下:",
            "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"
        }
    ]}
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # 此處以qwen-mt-plus為例,可按需更換模型名稱
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 版本需要不低於 2.20.6
import java.lang.System;
import java.util.Collections;
import java.util.Arrays;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.aigc.generation.TranslationOptions.Tm;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("通過如下命令可以看出安裝thrift的版本資訊;")
                .build();
        Tm tm1 = Tm.builder()
                .source("您可以通過如下方式查看叢集的核心版本資訊:")
                .target("You can use one of the following methods to query the engine version of a cluster:")
                .build();
        Tm tm2 = Tm.builder()
                .source("我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;")
                .target("The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website.")
                .build();
        Tm tm3 = Tm.builder()
                .source("您可以通過PyPI來安裝SDK,安裝命令如下:")
                .target("You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:")
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .tmList(Arrays.asList(tm1, tm2, tm3))
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-mt-plus")
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("錯誤資訊:"+e.getMessage());
        }
        System.exit(0);
    }
}

curl

# ======= 重要提示 =======
# 如果使用北京地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 執行時請刪除該注釋 ====

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-plus",
  "input": {
    "messages": [
      {
        "content": "通過如下命令可以看出安裝thrift的版本資訊;",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English",
      "tm_list":[
          {"source": "您可以通過如下方式查看叢集的核心版本資訊:", "target": "You can use one of the following methods to query the engine version of a cluster:"},
          {"source": "我們雲HBase的thrift環境是0.9.0,所以建議用戶端的版本也為 0.9.0,可以從這裡下載thrift的0.9.0 版本,下載的源碼包我們後面會用到,這裡需要先安裝thrift編譯環境,對於源碼安裝可以參考thrift官網;", "target": "The version of Thrift used by ApsaraDB for HBase is 0.9.0. Therefore, we recommend that you use Thrift 0.9.0 to create a client. Click here to download Thrift 0.9.0. The downloaded source code package will be used later. You must install the Thrift compiling environment first. For more information, see Thrift official website."},
          {"source": "您可以通過PyPI來安裝SDK,安裝命令如下:", "target": "You can run the following command in Python Package Index (PyPI) to install Elastic Container Instance SDK for Python:"}
      ]
  }
}'

領域提示

Python

import os
import dashscope

# 如果使用北京地區的模型,需要將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
    {
        "role": "user",
        "content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。"
    }
]
translation_options = {
    "source_lang": "Chinese",
    "target_lang": "English",
    "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."
}
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-mt-plus",  # 注意,qwen-mt-lite模型不支援領域提示功能
    messages=messages,
    result_format='message',
    translation_options=translation_options
)
print(response.output.choices[0].message.content)

Java

// DashScope SDK 版本需要不低於 2.20.6
import java.lang.System;
import java.util.Collections;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.aigc.generation.TranslationOptions;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        // 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。")
                .build();
        TranslationOptions options = TranslationOptions.builder()
                .sourceLang("auto")
                .targetLang("English")
                .domains("The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style.")
                .build();
        GenerationParam param = GenerationParam.builder()
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 注意,qwen-mt-lite模型不支援領域提示功能
                .model("qwen-mt-plus")
                .messages(Collections.singletonList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .translationOptions(options)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(result.getOutput().getChoices().get(0).getMessage().getContent());
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.err.println("錯誤資訊:"+e.getMessage());
        }
        System.exit(0);
    }
}

curl

# ======= 重要提示 =======
# 如果使用北京地區的模型,需要將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 執行時請刪除該注釋 ====

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen-mt-plus",
  "input": {
    "messages": [
      {
        "content": "第二個SELECT語句返回一個數字,表示在沒有LIMIT子句的情況下,第一個SELECT語句返回了多少行。",
        "role": "user"
      }
    ]
  },
  "parameters": {
    "translation_options": {
      "source_lang": "Chinese",
      "target_lang": "English",
      "domains": "The sentence is from Ali Cloud IT domain. It mainly involves computer-related software development and usage methods, including many terms related to computer software and hardware. Pay attention to professional troubleshooting terminologies and sentence patterns when translating. Translate into this IT domain style."}
  }
}'

model string (必選)

模型名稱。支援的模型:qwen-mt-plus、qwen-mt-flash、qwen-mt-lite、qwen-mt-turbo。

messages array (必選)

訊息數組,用於向大模型傳遞上下文。僅支援傳入 User Message。

訊息類型

User Message object (必選)

使用者訊息,用於傳遞待翻譯的句子。

屬性

content string(必選)

待翻譯的句子。

role string (必選)

使用者訊息的角色,必須設為user

max_tokens integer (可選)

用於限制模型輸出的最大 Token 數。若產生內容超過此值,響應將被截斷。

預設值與最大值均為模型的最大輸出長度,請參見模型選型

Java SDK中為maxTokens通過HTTP調用時,請將 max_tokens 放入 parameters 對象中。

seed integer (可選)

隨機數種子。用於確保在相同輸入和參數下產生結果可複現。若調用時傳入相同的 seed 且其他參數不變,模型將儘可能返回相同結果。

取值範圍:[0,231−1]

通過HTTP調用時,請將 seed 放入 parameters 對象中。

temperature float (可選) 預設值為0.65

採樣溫度,控制模型產生文本的多樣性。

temperature越高,產生的文本更多樣,反之,產生的文本更確定。

取值範圍: [0, 2)

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。

通過HTTP調用時,請將 temperature 放入 parameters 對象中。

top_p float (可選)預設值為0.8

核採樣的機率閾值,控制模型產生文本的多樣性。

top_p越高,產生的文本更多樣。反之,產生的文本更確定。

取值範圍:(0,1.0]

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。

Java SDK中為topP通過HTTP調用時,請將 top_p 放入 parameters 對象中。

repetition_penalty float (可選)預設值為1.0

模型產生時連續序列中的重複度。提高repetition_penalty時可以降低模型產生的重複度,1.0表示不做懲罰。沒有嚴格的取值範圍,只要大於0即可。

Java SDK中為repetitionPenalty通過HTTP調用時,請將 repetition_penalty 放入 parameters 對象中。

top_k integer (可選)預設值為1

產生過程中採樣候選集的大小。例如,取值為50時,僅將單次產生中得分最高的50個Token組成隨機採樣的候選集。取值越大,產生的隨機性越高;取值越小,產生的確定性越高。取值為None或當top_k大於100時,表示不啟用top_k策略,此時僅有top_p策略生效。

取值需要大於或等於0。

Java SDK中為topK通過HTTP調用時,請將 top_k 放入 parameters 對象中。

stream boolean (可選)

是否以流式方式輸出回複。

可選值:

  • false:等待模型產生完整回複後一次性返回。

  • true:模型邊產生邊返回資料區塊。用戶端需逐塊讀取,以還原完整回複。

說明

當前僅qwen-mt-flash、qwen-mt-lite模型支援以增量形式返回資料,每次返回僅包含新產生的內容。qwen-mt-plus和qwen-mt-turbo模型以非增量形式返回資料,每次返回當前已經產生的整個序列,暫時無法修改。如:

I

I didn

I didn't

I didn't laugh

I didn't laugh after

...

該參數僅支援Python SDK。通過Java SDK實現流式輸出請通過streamCall介面調用;通過HTTP實現流式輸出請在Header中指定X-DashScope-SSEenable

translation_options object (必選)

需配置的翻譯參數。

屬性

source_lang string (必選)

源語言的英文全稱,詳情請參見支援的語言。若設為auto,模型會自動識別輸入的語種。

target_lang string (必選)

目標語言的英文全稱,詳情請參見支援的語言

terms arrays (可選)

使用術語幹預功能時需設定的術語數組。

屬性

source string (必選)

源語言的術語。

target string (必選)

目標語言的術語。

tm_list arrays (可選)

使用翻譯記憶功能時需設定的翻譯記憶數組。

屬性

source string (必選)

源語言的語句。

target string (必選)

目標語言的語句。

domains string (可選)

使用領域提示功能時需設定的領域提示句。

領域提示句暫時只支援英文。
qwen-mt-lite模型不支援領域提示功能。
Java SDK中為translationOptions。通過HTTP調用時,請將 translation_options 放入 parameters 對象中。

chat響應對象(流式與非流式輸出格式一致)

{
  "status_code": 200,
  "request_id": "9b4ec3b2-6d29-40a6-a08b-7e3c9a51c289",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": "stop",
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "I didn't laugh after watching this video."
        }
      }
    ],
    "model_name": "qwen-mt-plus"
  },
  "usage": {
    "input_tokens": 53,
    "output_tokens": 9,
    "total_tokens": 62
  }
}

status_code string

本次請求的狀態代碼。200 表示請求成功,否則表示請求失敗。

Java SDK不會返回該參數。調用失敗會拋出異常,異常資訊為status_codemessage的內容。

request_id string

本次調用的唯一識別碼。

Java SDK返回參數為requestId。

code string

錯誤碼,調用成功時為空白值。

只有Python SDK返回該參數。

output object

調用結果資訊。

屬性

text string

該參數當前固定為null

finish_reason string

模型結束產生的原因。有以下情況:

  • 正在產生時為null

  • 模型輸出自然結束為stop

  • 因產生長度過長而結束為length

choices array

模型的輸出資訊。

屬性

finish_reason string

有以下情況:

  • 正在產生時為null

  • 因模型輸出自然結束為stop

  • 因產生長度過長而結束為length

message object

模型輸出的訊息對象。

屬性

role string

輸出訊息的角色,固定為assistant

content string

翻譯的結果。

usage object

本次請求使用的Token資訊。

屬性

input_tokens integer

輸入 Token 數。

output_tokens integer

輸出 Token 數。

total_tokens integer

總 Token 數,為input_tokensoutput_tokens之和

錯誤碼

如果模型調用失敗並返回報錯資訊,請參見錯誤資訊進行解決。