全部產品
Search
文件中心

Alibaba Cloud Model Studio:通義千問API參考

更新時間:Dec 11, 2025

本文介紹通義千問 API 的輸入與輸出參數,並提供 Python 等主流語言在典型情境下的調用樣本。

模型介紹、選型建議和使用方法請參考文本產生模型概述

可通過 OpenAI 相容或 DashScope 協議調用通義千問 API。

OpenAI 相容

新加坡地區

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

HTTP 要求地址:POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

北京地區

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

HTTP 要求地址:POST https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions

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

請求體

POST /chat/completions

OpenAI 相容介面線上調試

POST https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions

文本輸入

Python

import os
from openai import OpenAI


client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",  
)

completion = client.chat.completions.create(
    # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    model="qwen-plus",
    messages=[
        {"role": "system", "content": "You are a helpful assistant."},
        {"role": "user", "content": "你是誰?"},
    ],
    # Qwen3模型通過enable_thinking參數控制思考過程(開源版預設True,商業版預設False)
    # 使用Qwen3開源版模型時,若未啟用流式輸出,請將下行取消注釋,否則會報錯
    # extra_body={"enable_thinking": False},
)
print(completion.model_dump_json())

Java

請求樣本

// 該代碼 OpenAI SDK 版本為 2.6.0
import com.openai.client.OpenAIClient;
import com.openai.client.okhttp.OpenAIOkHttpClient;
import com.openai.models.chat.completions.ChatCompletion;
import com.openai.models.chat.completions.ChatCompletionCreateParams;

public class Main {
    public static void main(String[] args) {
        OpenAIClient client = OpenAIOkHttpClient.builder()
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
                .baseUrl("https://dashscope-intl.aliyuncs.com/compatible-mode/v1") 
                .build();

        ChatCompletionCreateParams params = ChatCompletionCreateParams.builder()
                .addUserMessage("你是誰")
                .model("qwen-plus")
                .build();

        try {
            ChatCompletion chatCompletion = client.chat().completions().create(params);
            System.out.println(chatCompletion);
        } catch (Exception e) {
            System.err.println("Error occurred: " + e.getMessage());
            e.printStackTrace();
        }
    }
}

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        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" 
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus",  //此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        messages: [
            { role: "system", content: "You are a helpful assistant." },
            { role: "user", content: "你是誰?" }
        ],
    });
    console.log(JSON.stringify(completion))
}

main();

Go

package main

import (
	"context"
	"os"

	"github.com/openai/openai-go"
	"github.com/openai/openai-go/option"
)

func main() {
	client := openai.NewClient(
	        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
		option.WithAPIKey(os.Getenv("DASHSCOPE_API_KEY")), // defaults to os.LookupEnv("OPENAI_API_KEY")
		// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/
		option.WithBaseURL("https://dashscope-intl.aliyuncs.com/compatible-mode/v1/"), 
	)
	chatCompletion, err := client.Chat.Completions.New(
		context.TODO(), openai.ChatCompletionNewParams{
			Messages: openai.F(
				[]openai.ChatCompletionMessageParamUnion{
					openai.UserMessage("你是誰"),
				},
			),
			Model: openai.F("qwen-plus"),
		},
	)

	if err != nil {
		panic(err.Error())
	}

	println(chatCompletion.Choices[0].Message.Content)
}

C#(HTTP)

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 若沒有配置環境變數,請用百鍊API Key將下行替換為:string? apiKey = "sk-xxx";
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key 未設定。請確保環境變數 'DASHSCOPE_API_KEY' 已設定。");
            return;
        }

        // 佈建要求 URL 和內容
        // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
        string url = "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions";
        // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"",
            ""messages"": [
                {
                    ""role"": ""system"",
                    ""content"": ""You are a helpful assistant.""
                },
                {
                    ""role"": ""user"", 
                    ""content"": ""你是誰?""
                }
            ]
        }";

        // 發送請求並擷取響應
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 輸出結果
        Console.WriteLine(result);
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            // 佈建要求頭
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // 發送請求並擷取響應
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // 處理響應
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"請求失敗: {response.StatusCode}";
            }
        }
    }
}

PHP(HTTP)

<?php
// 佈建要求的URL
// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
$url = 'https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions';
// 若沒有配置環境變數,請用百鍊API Key將下行替換為:$apiKey = "sk-xxx";
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
// 佈建要求頭
$headers = [
    'Authorization: Bearer '.$apiKey,
    'Content-Type: application/json'
];
// 佈建要求體
$data = [
    // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    "model" => "qwen-plus",
    "messages" => [
        [
            "role" => "system",
            "content" => "You are a helpful assistant."
        ],
        [
            "role" => "user",
            "content" => "你是誰?"
        ]
    ]
];
// 初始化cURL會話
$ch = curl_init();
// 設定cURL選項
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($data));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, $headers);
// 執行cURL會話
$response = curl_exec($ch);
// 檢查是否有錯誤發生
if (curl_errno($ch)) {
    echo 'Curl error: ' . curl_error($ch);
}
// 關閉cURL資源
curl_close($ch);
// 輸出響應結果
echo $response;
?>

curl

新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key。若使用北京地區的模型,需將url替換為: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-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "你是誰?"
        }
    ]
}'

流式輸出

更多用法請參見流式輸出

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-plus",  # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    messages=[{'role': 'system', 'content': 'You are a helpful assistant.'},
                {'role': 'user', 'content': '你是誰?'}],
    stream=True,
    stream_options={"include_usage": True}
    )
for chunk in completion:
    print(chunk.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        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"
    }
);

async function main() {
    const completion = await openai.chat.completions.create({
        model: "qwen-plus", // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        messages: [
            {"role": "system", "content": "You are a helpful assistant."},
            {"role": "user", "content": "你是誰?"}
        ],
        stream: true,
    });
    for await (const chunk of completion) {
        console.log(JSON.stringify(chunk));
    }
}

main();

curl

新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key 如果使用北京地區的模型,請將url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1/chat/completions
curl --location "https://dashscope-intl.aliyuncs.com/compatible-mode/v1/chat/completions" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "你是誰?"
        }
    ],
    "stream":true
}'

映像輸入

關於大模型分析映像的更多用法,請參見視覺理解

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
    model="qwen-vl-plus",  # 此處以qwen-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
    messages=[{"role": "user","content": [
            {"type": "image_url",
             "image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            {"type": "text", "text": "這是什麼"},
            ]}]
    )
print(completion.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        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"
    }
);

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen-vl-max", // 此處以qwen-vl-max為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
        messages: [{role: "user",content: [
            { type: "image_url",image_url: {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
            { type: "text", text: "這是什嗎?" },
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();

curl

新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key 如果使用北京地區的模型,請將url替換為: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-vl-plus",
  "messages": [{
      "role": "user",
      "content": [
       {"type": "image_url","image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"}},
       {"type": "text","text": "這是什麼"}
       ]}]
}'

視頻輸入

以下為傳入圖片列表的範例程式碼,關於更多用法(如傳入的視訊檔案),請參見視覺理解

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",  
)
completion = client.chat.completions.create(
    # 此處以qwen-vl-max為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
    model="qwen-vl-max",
    messages=[{
        "role": "user",
        "content": [
            {
                "type": "video",
                "video": [
                    "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                    "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"]
            },
            {
                "type": "text",
                "text": "描述這個視頻的具體過程"
            }]}]
)
print(completion.model_dump_json())

Node.js

// 確保之前在 package.json 中指定了 "type": "module"
import OpenAI from "openai"; 

const openai = new OpenAI({
    // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
    // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    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"    
});

async function main() {
    const response = await openai.chat.completions.create({
        // 此處以qwen-vl-max為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models 
        model: "qwen-vl-max",
        messages: [{
            role: "user",
            content: [
                {
                    type: "video",
                    video: [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    type: "text",
                    text: "描述這個視頻的具體過程"
                }
        ]}]
    });
    console.log(JSON.stringify(response));
}

main();

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key。以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為: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-vl-max",
    "messages": [
        {
            "role": "user",
            "content": [
                {
                    "type": "video",
                    "video": [
                        "https://img.alicdn.com/imgextra/i3/O1CN01K3SgGo1eqmlUgeE9b_!!6000000003923-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01BjZvwg1Y23CF5qIRB_!!6000000003000-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i4/O1CN01Ib0clU27vTgBdbVLQ_!!6000000007859-0-tps-3840-2160.jpg",
                        "https://img.alicdn.com/imgextra/i1/O1CN01aygPLW1s3EXCdSN4X_!!6000000005710-0-tps-3840-2160.jpg"
                    ]
                },
                {
                    "type": "text",
                    "text": "描述這個視頻的具體過程"
                }
            ]
        }
    ]
}'

工具調用

完整的Function Calling 流程代碼請參見Function Calling
Qwen3(思考模式)與QwQ 模型的 Function Calling 代碼請參見深度思考

Python

import os
from openai import OpenAI

client = OpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",  
)

tools = [
    # 工具1 擷取當前時刻的時間
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "當你想知道現在的時間時非常有用。",
            "parameters": {}  # 因為擷取目前時間無需輸入參數,因此parameters為空白字典
        }
    },  
    # 工具2 擷取指定城市的天氣
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "當你想查詢指定城市的天氣時非常有用。",
            "parameters": {  
                "type": "object",
                "properties": {
                    # 查詢天氣時需要提供位置,因此參數設定為location
                    "location": {
                        "type": "string",
                        "description": "城市或縣區,比如北京市、杭州市、餘杭區等。"
                    }
                },
                "required": ["location"]
            }
        }
    }
]
messages = [{"role": "user", "content": "杭州天氣怎麼樣"}]
completion = client.chat.completions.create(
    model="qwen-plus",  # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    messages=messages,
    tools=tools
)

print(completion.model_dump_json())

Node.js

import OpenAI from "openai";

const openai = new OpenAI(
    {
        // 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey: "sk-xxx",
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        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 messages = [{"role": "user", "content": "杭州天氣怎麼樣"}];
const tools = [
// 工具1 擷取當前時刻的時間
{
    "type": "function",
    "function": {
        "name": "get_current_time",
        "description": "當你想知道現在的時間時非常有用。",
        // 因為擷取目前時間無需輸入參數,因此parameters為空白
        "parameters": {}  
    }
},  
// 工具2 擷取指定城市的天氣
{
    "type": "function",
    "function": {
        "name": "get_current_weather",
        "description": "當你想查詢指定城市的天氣時非常有用。",
        "parameters": {  
            "type": "object",
            "properties": {
                // 查詢天氣時需要提供位置,因此參數設定為location
                "location": {
                    "type": "string",
                    "description": "城市或縣區,比如北京市、杭州市、餘杭區等。"
                }
            },
            "required": ["location"]
        }
    }
}
];

async function main() {
    const response = await openai.chat.completions.create({
        model: "qwen-plus", // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        messages: messages,
        tools: tools,
    });
    console.log(JSON.stringify(response));
}

main();

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key。以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為: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-plus",
    "messages": [
        {
            "role": "system",
            "content": "You are a helpful assistant."
        },
        {
            "role": "user", 
            "content": "杭州天氣怎麼樣"
        }
    ],
    "tools": [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "當你想知道現在的時間時非常有用。",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "當你想查詢指定城市的天氣時非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location":{
                        "type": "string",
                        "description": "城市或縣區,比如北京市、杭州市、餘杭區等。"
                    }
                },
                "required": ["location"]
            }
        }
    }
  ]
}'

非同步呼叫

import os
import asyncio
from openai import AsyncOpenAI
import platform

client = AsyncOpenAI(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 如果使用華北2(北京)地區的模型,需要使用華北2(北京)地區的 API KEY,擷取連結:https://bailian.console.alibabacloud.com/?tab=model#/api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/v1
    base_url="https://dashscope-intl.aliyuncs.com/compatible-mode/v1",
)

async def main():
    response = await client.chat.completions.create(
        messages=[{"role": "user", "content": "你是誰"}],
        model="qwen-plus",  # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    )
    print(response.model_dump_json())

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

model string (必選)

模型名稱。

支援的模型:Qwen 大語言模型(商業版、開源版)、Qwen-VL、Qwen-Coder、Qwen-Omni、Qwen-Math。

具體模型名稱和計費,請參見模型列表

messages array (必選)

傳遞給大模型的上下文,按對話順序排列。

訊息類型

System Message object (可選)

系統訊息,用於設定大模型的角色、語氣、任務目標或約束條件等。一般放在messages數組的第一位。

QwQ 模型不建議設定 System Message,QVQ 模型設定 System Message不會生效。

屬性

content string (必選)

系統指令,用於明確模型的角色、行為規範、回答風格和任務約束等。

role string (必選)

系統訊息的角色,固定為system

User Message object (必選)

使用者訊息,用於向模型傳遞問題、指令或上下文等。

屬性

content string 或 array (必選)

訊息內容。若輸入只有文本,則為 string 類型;若輸入包含映像等多模態資料,或啟用顯式緩衝,則為 array 類型。

使用多模態模型或啟用顯式緩衝時的屬性

type string (必選)

可選值:

  • text

    輸入文本時需設為text

  • image_url

    輸入圖片時需設為image_url

  • input_audio

    輸入音頻時需設為input_audio

  • video

    輸入圖片列表形式的視頻時需設為video

  • video_url

    輸入視頻檔案時需設為video_url

    Qwen-VL僅部分模型可輸入視頻檔案,詳情參見視頻理解(Qwen-VL);QVQ與Qwen-Omni 模型支援直接傳入的視訊檔案。

text string

輸入的文本。當typetext時,是必選參數。

image_url object

輸入的圖片資訊。當typeimage_url時是必選參數。

屬性

url string(必選)

圖片的 URL或 Base64 Data URL。傳入本地檔案請參考視覺理解

input_audio object

輸入的音頻資訊。當typeinput_audio時是必選參數。

屬性

data string(必選)

音訊 URL 或Base64 Data URL。傳入本地檔案請參見:輸入 Base 64 編碼的本地檔案

format string(必選)

輸入音訊格式,如mp3wav等。

video array

輸入的圖片列表形式的視頻資訊。當typevideo時是必選參數。使用方法請參見:視頻理解(Qwen-VL)視頻理解(QVQ)視頻理解(Qwen-Omni)

樣本值:

[
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
    "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
]

video_url object

輸入的視頻檔案資訊。當typevideo_url時是必選參數。

Qwen-VL 只可理解視頻檔案的視覺資訊,Qwen-Omni 可理解視頻檔案中的視覺與音頻資訊。

屬性

url string(必選)

視頻檔案的公網 URL 或 Base64 Data URL。輸入本地視頻檔案請參見輸入 Base 64 編碼的本地檔案

min_pixels integer (可選)

設定輸入映像的最小像素閾值。當輸入映像或視訊框架的像素小於min_pixels時,會將其進行放大,直到總像素高於min_pixels

  • 適用模型:QVQ、Qwen-VL

  • 取值範圍:如下所示

    min_pixels 取值範圍

    • Qwen3-VL:預設值和最小值均為:65536

    • qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815:預設值和最小值均為4096

    • QVQ 及其他 Qwen2.5-VL 模型:預設值和最小值均為3136

  • 樣本值:{"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"min_pixels": 65536}

max_pixels integer (可選)

用於設定輸入映像或視訊框架的最大像素閾值。當輸入映像或視頻的像素在[min_pixels, max_pixels]區間內時,模型會按原圖進行識別。當輸入映像像素大於max_pixels時,會將映像進行縮小,直到總像素低於max_pixels

  • 適用模型:QVQ、Qwen-VL

  • 取值範圍:如下所示

    max_pixels 取值範圍

    max_pixels的取值與是否開啟vl_high_resolution_images參數有關。

    • vl_high_resolution_imagesFalse時:

      • Qwen3-VL:預設值為26214402560 * 32 * 32,最大值為:16777216

      • qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815:預設值為1310720,最大值為:16777216

      • QVQ及其他Qwen2.5-VL模型:預設值為1003520 ,最大值為12845056

    • vl_high_resolution_imagesTrue時:

      • Qwen3-VLqwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815max_pixels無效,輸入映像的最大像素固定為16777216

      • QVQ及其他Qwen2.5-VL模型:max_pixels無效,輸入映像的最大像素固定為12845056

  • 樣本值:{"type": "image_url","image_url": {"url":"https://xxxx.jpg"},"max_pixels": 8388608}

cache_control object (可選)

用於開啟顯式緩衝。相關文檔:顯式緩衝

屬性

type string(必選)

僅支援設定為ephemeral

role string (必選)

使用者訊息的角色,固定為user

Assistant Message object (可選)

模型的回複。通常用於在多輪對話中作為上下文回傳給模型。

屬性

content string (可選)

模型回複的常值內容。包含tool_calls時,content可以為空白;否則content為必選。

role string (必選)

助手訊息的角色,固定為assistant

partial boolean (可選)預設值為false

是否開啟首碼續寫

可選值:

  • true:開啟;

  • false:不開啟。

支援的模型

  • 通義千問Max 系列

    qwen3-max、qwen3-max-2025-09-23、qwen3-max-preview(非思考模式)、qwen-max、qwen-max-latest、qwen-max-2025-01-25及之後的快照模型

  • 通義千問Plus 系列(非思考模式)

    qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25及之後的快照模型

  • 通義千問Flash 系列(非思考模式)

    qwen-flash、qwen-flash-2025-07-28及之後的快照模型

  • 通義千問Coder 系列

    qwen3-coder-plus、qwen3-coder-flash、qwen3-coder-480b-a35b-instruct、qwen3-coder-30b-a3b-instruct

  • 通義千問VL 系列

    • qwen3-vl-plus 系列(非思考模式)

      qwen3-vl-plus、qwen3-vl-plus-2025-09-23及之後的快照模型

    • qwen3-vl-flash 系列(非思考模式)

      qwen3-vl-flash、qwen3-vl-flash-2025-10-15及之後的快照模型

    • qwen-vl-max 系列

      qwen-vl-max、qwen-vl-max-latest、qwen-vl-max-2025-04-08及之後的快照模型

    • qwen-vl-plus 系列

      qwen-vl-plus、qwen-vl-plus-latest、qwen-vl-plus-2025-01-25及之後的快照模型

  • 通義千問Turbo 系列(非思考模式)

    qwen-turbo、qwen-turbo-latest、qwen-turbo-2024-11-01及之後的快照模型

  • 通義千問開源系列

    Qwen3 開源模型(非思考模式)、Qwen2.5系列的文本模型、Qwen3-VL開源模型(非思考模式)

tool_calls array (可選)

發起 Function Calling 後,返回的工具與入參資訊,包含一個或多個對象。由上一輪模型響應的tool_calls欄位獲得。

屬性

id string (必選)

工具響應的ID。

type string(必選)

工具類型,當前只支援設為function

function object(必選)

工具與入參資訊。

屬性

name string(必選)

工具名稱。

arguments string(必選)

入參資訊,為JSON格式字串。

index integer(必選)

當前工具資訊在tool_calls數組中的索引。

Tool Message object (可選)

工具的輸出資訊。

屬性

content string (必選)

工具函數的輸出內容,必須為字串。若工具返回結構化資料(如JSON),需將其序列化為字串。

role string (必選)

固定為tool

tool_call_id string (必選)

發起 Function Calling 後返回的 id,通過completion.choices[0].message.tool_calls[$index].id擷取,用於標記 Tool Message 對應的工具。

stream boolean (可選) 預設值為 false

是否以流式輸出方式回複。相關文檔:流式輸出

可選值:

  • false:模型產生全部內容後一次性返回;

  • true:邊產生邊輸出,每產生一部分內容即返回一個資料區塊(chunk)。需即時逐個讀取這些塊以拼接完整回複。

推薦設定為true,可提升閱讀體驗並降低逾時風險。

stream_options object (可選)

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

屬性

include_usage boolean (可選)預設值為false

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

可選值:

  • true:包含;

  • false:不包含。

流式輸出時,Token 消耗資訊僅可出現在響應的最後一個資料區塊。

modalities array (可選)預設值為["text"]

輸出資料的模態,僅適用於 Qwen-Omni 模型。相關文檔:全模態

可選值:

  • ["text","audio"]:輸出文本與音頻;

  • ["text"]:僅輸出文本。

audio object (可選)

輸出音訊音色與格式,僅適用於 Qwen-Omni 模型,且modalities參數需為["text","audio"]。相關文檔:全模態

屬性

voice string (必選)

輸出音訊音色。請參見音色列表

format string (必選)

輸出音訊格式,僅支援設定為wav

temperature float (可選)

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

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

取值範圍: [0, 2)

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。更多說明,請參見文本產生模型概述

不建議修改QVQ模型的預設temperature值 。

top_p float (可選)

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

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

取值範圍:(0,1.0]

temperature與top_p均可以控制產生文本的多樣性,建議只設定其中一個值。更多說明,請參見文本產生模型概述

不建議修改QVQ模型的預設 top_p 值。

top_k integer (可選)

指定產生過程中用於採樣的候選 Token 數量。值越大,輸出越隨機;值越小,輸出越確定。若設為 null 或大於 100,則禁用 top_k 策略,僅 top_p 策略生效。取值必須為大於或等於 0 的整數。

top_k預設值

QVQ系列、qwen-vl-plus-2025-07-10、qwen-vl-plus-2025-08-15:10;

QwQ 系列:40;

其餘qwen-vl-plus系列、qwen-vl-max-2025-08-13之前的模型、qwen2.5-omni-7b:1;

Qwen3-Omni-Flash系列:50;

其餘模型均為20。

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"top_k":xxx}。
不建議修改QVQ模型的預設 top_k 值。

presence_penalty float (可選)

控制模型產生文本時的內容重複度。

取值範圍:[-2.0, 2.0]。正值降低重複度,負值增加重複度。

在創意寫作或頭腦風暴等需要多樣性、趣味性或創造力的情境中,建議調高該值;在技術文檔或正式文本等強調一致性與術語準確性的情境中,建議調低該值。

presence_penalty預設值

qwen3-max-preview(思考模式)、Qwen3(非思考模式)、Qwen3-Instruct系列、qwen3-0.6b/1.7b/4b(思考模式)、QVQ系列、qwen-max、qwen-max-latest、qwen-max-latestqwen2.5-vl系列、qwen-vl-max系列、qwen-vl-plus、Qwen3-VL(非思考):1.5;

qwen-vl-plus-latest、qwen-vl-plus-2025-08-15:1.2

qwen-vl-plus-2025-01-25:1.0;

qwen3-8b/14b/32b/30b-a3b/235b-a22b(思考模式)、qwen-plus/qwen-plus-latest/2025-04-28(思考模式)、qwen-turbo/qwen-turbo/2025-04-28(思考模式):0.5;

其餘均為0.0。

原理介紹

如果參數值是正數,模型將對目前文本中已存在的Token施加一個懲罰值(懲罰值與文本出現的次數無關),減少這些Token重複出現的幾率,從而減少內容重複度,增加用詞多樣性。

樣本

提示詞:把這句話翻譯成中文“This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good.”

參數值為2.0:這部電影很好。劇情很棒,演技棒,音樂也非常好聽,總的來說,整部電影都好得不得了。實際上它真的很優秀。劇情非常精彩,演技出色,音樂也是那麼的動聽。

參數值為0.0:這部電影很好。劇情好,演技好,音樂也好,總的來說,整部電影都很好。事實上,它真的很棒。劇情非常好,演技也非常出色,音樂也同樣優秀。

參數值為-2.0:這部電影很好。情節很好,演技很好,音樂也很好,總的來說,整部電影都很好。實際上,它真的很棒。情節非常好,演技也非常好,音樂也非常好。

使用qwen-vl-plus-2025-01-25模型進行文字提取時,建議設定presence_penalty為1.5。
不建議修改QVQ模型的預設presence_penalty值。

response_format object (可選) 預設值為{"type": "text"}

返回內容的格式。可選值:

  • {"type": "text"}:輸出文字回複;

  • {"type": "json_object"}:輸出標準格式的JSON字串。相關文檔:結構化輸出

若指定為{"type": "json_object"},需在提示詞中明確指示模型輸出JSON,如:“請按照json格式輸出”,否則會報錯。

支援的模型

  • 文本產生模型

    • 通義千問Max 系列:qwen3-max、qwen3-max-2025-09-23、qwen3-max-preview(非思考模式)qwen-max、qwen-max-latest、qwen-max-2025-01-25 及之後的快照模型

    • 通義千問Plus 系列(非思考模式):qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25及之後的快照模型

    • 通義千問Flash 系列(非思考模式):qwen-flash、qwen-flash-2025-07-28及之後的快照模型

    • 通義千問Turbo 系列(非思考模式):qwen-turbo、qwen-turbo-latest、qwen-turbo-2024-11-01及之後的快照模型

    • 通義千問Coder 系列:qwen3-coder-plus、qwen3-coder-plus-2025-07-22、qwen3-coder-flash、qwen3-coder-flash-2025-07-28

    • 通義千問Long 系列:qwen-long-latest、qwen-long-2025-01-25

  • 文本產生開源模型

    • Qwen3(非思考模式)

    • Qwen3-Coder

    • Qwen2.5 系列的文本模型(不含math與coder模型)

  • 多模態模型

    • 通義千問3-VL-Plus 系列(非思考模式):qwen3-vl-plus、qwen3-vl-plus-2025-09-23及之後的快照模型

    • 通義千問3-VL-Flash 系列(非思考模式):qwen3-vl-flash、qwen3-vl-flash-2025-10-15及之後的快照模型

    • 通義千問VL-Max 系列:qwen-vl-max(不包括最新版與快照版模型)

    • 通義千問VL-Plus 系列:qwen-vl-plus(不包括最新版與快照版模型)

  • 多模態開源模型

    • Qwen3-VL(非思考模式)

說明

思考模式的模型暫不支援結構化輸出功能。

max_input_tokens integer (可選)

允許輸入的最大 Token 長度。目前僅支援qwen-plus-0728/latest模型。

  • qwen-plus-latest 預設值:129,024

    後續預設值可能調整至1,000,000。
  • qwen-plus-2025-07-28 預設值:1,000,000

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"max_input_tokens": xxx}

max_tokens integer (可選)

用於限制模型輸出的最大 Token 數。若產生內容超過此值,產生將提前停止,且返回的finish_reasonlength

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

適用於需控制輸出長度的情境,如產生摘要、關鍵詞,或用於降低成本、縮短回應時間。

觸發 max_tokens 時,響應的 finish_reason 欄位為 length

max_tokens不限制思考模型思維鏈的長度。

vl_high_resolution_images boolean (可選)預設值為false

是否將輸入映像的像素上限提升至 16384 Token 對應的像素值。相關文檔:處理高解析度映像

  • vl_high_resolution_images:true,使用固定解析度策略,忽略 max_pixels 設定,超過此解析度時會將映像總像素縮小至此上限內。

    點擊查看各模型像素上限

    vl_high_resolution_imagesTrue時,不同模型像素上限不同:

    • Qwen3-VL系列qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815模型:16777216(每Token對應32*32像素,即16384*32*32

    • QVQ系列、其他Qwen2.5-VL系列模型:12845056(每Token對應28*28像素,即 16384*28*28

  • vl_high_resolution_imagesfalse,實際解析度由 max_pixels 與預設上限共同決定,取二者計算結果的最大值。超過此像素上限時會將映像縮小至此上限內。

    點擊查看各模型的預設像素上限

    vl_high_resolution_imagesfalse時,不同模型預設像素上限不同:

    • Qwen3-VL系列2621440(2560*32*32,即預設Token上限為2560)

    • qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815模型:1310720(1280*32*32,即預設Token上限為1280)

    • QVQ系列、其他Qwen2.5-VL系列模型:1003520(1280*28*28,即預設Token上限為1280)

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"vl_high_resolution_images":xxx}。

n integer (可選) 預設值為1

產生響應的數量,取值範圍是1-4。適用於需產生多個候選響應的情境,例如創意寫作或廣告文案。

僅支援 qwen-plus、 Qwen3(非思考模式) 模型。
若傳入 tools 參數, 請將n 設為 1。
增大 n 會增加輸出 Token 的消耗,但不增加輸入 Token 消耗。

enable_thinking boolean (可選)

使用混合思考(回複前既可思考也可不思考)模型時,是否開啟思考模式。適用於 Qwen3 、Qwen3-Omni-Flash、Qwen3-VL模型。相關文檔:深度思考

可選值:

  • true:開啟

    開啟後,思考內容將通過reasoning_content欄位返回。
  • false:不開啟

不同模型的預設值:支援的模型

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"enable_thinking": xxx}

thinking_budget integer (可選)

思考過程的最大 Token 數。適用於Qwen3-VL、Qwen3 的商業版與開源版模型。相關文檔:限制思考長度

預設值為模型最大思維鏈長度,請參見:模型列表

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"thinking_budget": xxx}

enable_code_interpreter boolean (可選)預設值為 false

是否開啟代碼解譯器功能。僅當modelqwen3-max-previewenable_thinkingtrue時生效。相關文檔:代碼解譯器

可選值:

  • true:開啟

  • false:不開啟

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"enable_code_interpreter": xxx}

seed integer (可選)

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

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

logprobs boolean (可選)預設值為 false

是否返回輸出 Token 的對數機率,可選值:

  • true

    返回

  • false

    不返回

思考階段產生的內容(reasoning_content)不會返回對數機率。

支援的模型

  • qwen-plus系列的快照模型(不包含主線模型)

  • qwen-turbo 系列的快照模型(不包含主線模型)

  • Qwen3 開源模型

top_logprobs integer (可選)預設值為0

指定在每一步產生時,返回模型最大機率的候選 Token 個數。

取值範圍:[0,5]

僅當 logprobstrue 時生效。

stop string 或 array (可選)

用於指定停止詞。當模型產生的文本中出現stop 指定的字串或token_id時,產生將立即終止。

可傳入敏感詞以控制模型的輸出。

stop為數組時,不可將token_id和字串同時作為元素輸入,比如不可以指定為["你好",104307]

tools array (可選)

包含一個或多個工具對象的數組,供模型在 Function Calling 中調用。相關文檔:Function Calling

設定 tools 且模型判斷需要調用工具時,響應會通過 tool_calls 返回工具資訊。

屬性

type string (必選)

工具類型,當前僅支援設為function

function object (必選)

屬性

name string (必選)

工具名稱。僅允許字母、數字、底線(_)和短劃線(-),最長 64 個 Token。

description string (必選)

工具描述資訊,協助模型判斷何時以及如何調用該工具。

parameters object (必選)

工具的參數描述,需要是一個合法的JSON Schema。JSON Schema的描述可以見連結。若parameters參數為空白,表示該工具沒有入參(如時間查詢工具)。

tool_choice string 或 object (可選)預設值為 auto

工具選擇策略。若需對某類問題強制指定工具調用方式(例如始終使用某工具或禁用所有工具),可設定此參數。

可選值:

  • auto

    大模型自主選擇工具策略。

  • none

    若不希望進行工具調用,可設定tool_choice參數為none

  • {"type": "function", "function": {"name": "the_function_to_call"}}

    若希望強制調用某個工具,可設定tool_choice參數為{"type": "function", "function": {"name": "the_function_to_call"}},其中the_function_to_call是指定的工具函數名稱。

    思考模式的模型不支援強制調用某個工具。

parallel_tool_calls boolean (可選)預設值為 false

是否開啟並行工具調用。相關文檔:並行工具調用

可選值:

  • true:開啟

  • false:不開啟

enable_search boolean (可選)預設值為 false

是否開啟連網搜尋。相關文檔:連網搜尋

可選值:

  • true:開啟;

    若開啟後未連網搜尋,可最佳化提示詞,或設定search_options中的forced_search參數開啟強制搜尋。
  • false:不開啟。

啟用互連網搜尋功能可能會增加 Token 的消耗。
該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"enable_search": True}

search_options object (可選)

連網搜尋的策略。相關文檔:連網搜尋

屬性

forced_search boolean(可選)預設值為false

是否強制開啟連網搜尋,僅當enable_searchtrue時生效。

可選值:

  • true:強制開啟;

  • false:不強制開啟,由模型判斷是否連網搜尋。

search_strategy string(可選)預設值為turbo

搜尋量級策略,僅當enable_searchtrue時生效。

可選值:

  • turbo (預設): 兼顧響應速度與搜尋效果,適用於大多數情境。

  • max: 採用更全面的搜尋策略,可調用多源搜尋引擎,以擷取更詳盡的搜尋結果,但回應時間可能更長。

  • agent:可多次調用連網搜尋工具與大模型,實現多輪資訊檢索與內容整合。

    agent策略僅適用於 qwen3-max 與 qwen3-max-2025-09-23。
    agent策略不可與其他連網搜尋策略同時設定。

enable_search_extension boolean(可選)預設值為false

是否開啟垂域搜尋,僅當enable_searchtrue時生效。

可選值:

  • true:開啟。

  • false:不開啟。

該參數非OpenAI標準參數。通過 Python SDK調用時,請放入 extra_body 對象中。配置方式為:extra_body={"search_options": xxx}

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

{
    "choices": [
        {
            "message": {
                "role": "assistant",
                "content": "我是阿里雲開發的一款超大規模語言模型,我叫通義千問。"
            },
            "finish_reason": "stop",
            "index": 0,
            "logprobs": null
        }
    ],
    "object": "chat.completion",
    "usage": {
        "prompt_tokens": 3019,
        "completion_tokens": 104,
        "total_tokens": 3123,
        "prompt_tokens_details": {
            "cached_tokens": 2048
        }
    },
    "created": 1735120033,
    "system_fingerprint": null,
    "model": "qwen-plus",
    "id": "chatcmpl-6ada9ed2-7f33-9de2-8bb0-78bd4035025a"
}

id string

本次調用的唯一識別碼。

choices array

模型產生內容的數組。

屬性

finish_reason string

模型停止產生的原因。

有三種情況:

  • 觸發輸入參數中的stop參數,或自然停止輸出時為stop

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

  • 需要調用工具而結束為tool_calls

index integer

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

logprobs object

模型輸出的 Token 機率資訊。

屬性

content array

包含每個 Token 及其對數機率的數組。

屬性

token string

當前 Token 的文本。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容(例如Emoji或中文字元)。

logprob float

當前 Token 的對數機率。傳回值為 null 表示機率值極低。

top_logprobs array

當前 Token 位置最可能的若干候選 Token,數量與請求參數top_logprobs保持一致。每個元素包含:

屬性

token string

候選 Token 文本。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容(例如Emoji或中文字元)。

logprob float

該候選 Token 的對數機率。傳回值為 null 表示機率值極低。

message object

模型輸出的訊息。

屬性

content string

模型的回複內容。

reasoning_content string

模型的思維鏈內容。

refusal string

該參數當前固定為null

role string

訊息的角色,固定為assistant

audio object

該參數當前固定為null

function_call(即將廢棄)object

該值固定為null,請參考tool_calls參數。

tool_calls array

在發起 Function Calling後,模型產生的工具與入參資訊。

屬性

id string

本次工具響應的唯一識別碼。

type string

工具類型,當前只支援function

function object

工具資訊。

屬性

name string

工具名稱。

arguments string

入參資訊,為JSON格式字串。

由於大模型響應有一定隨機性,輸出的入參資訊可能不符合函數簽名。請在調用前校正參數有效性

index integer

當前工具在tool_calls數組中的索引。

created integer

請求建立時的 Unix 時間戳記(秒)。

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

使用Qwen-VL 模型時輸出Token的細粒度分類。

屬性

audio_tokens integer

該參數當前固定為null

reasoning_tokens integer

該參數當前固定為null

text_tokens integer

Qwen-VL 模型輸出文本的Token數。

prompt_tokens_details object

輸入 Token 的細粒度分類。

屬性

audio_tokens integer

該參數當前固定為null

cached_tokens integer

命中 Cache 的 Token 數。Context Cache 詳情請參見上下文緩衝

text_tokens integer

Qwen-VL 模型輸入的文本 Token 數。

image_tokens integer

Qwen-VL 模型輸入的映像 Token數。

video_tokens integer

Qwen-VL 模型輸入的視頻檔案或者映像列表 Token 數。

cache_creation object

顯式緩衝建立資訊。

屬性

ephemeral_5m_input_tokens integer

建立顯式緩衝的 Token 數。

cache_creation_input_tokens integer

建立顯式緩衝的 Token 數。

cache_type string

使用顯式緩衝時,參數值為ephemeral,否則該參數不存在。

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

{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":"assistant","tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"我是","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"來自","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"阿里","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"雲的超大規模","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"語言模型,我","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"叫通義千","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"問。","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":null,"index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[{"delta":{"content":"","function_call":null,"refusal":null,"role":null,"tool_calls":null},"finish_reason":"stop","index":0,"logprobs":null}],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":null}
{"id":"chatcmpl-e30f5ae7-3063-93c4-90fe-beb5f900bd57","choices":[],"created":1735113344,"model":"qwen-plus","object":"chat.completion.chunk","service_tier":null,"system_fingerprint":null,"usage":{"completion_tokens":17,"prompt_tokens":22,"total_tokens":39,"completion_tokens_details":null,"prompt_tokens_details":{"audio_tokens":null,"cached_tokens":0}}}

id string

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

choices array

模型產生內容的數組,可包含一個或多個對象。若設定include_usage參數為true,則choices在最後一個chunk中為空白數組。

屬性

delta object

請求的增量對象。

屬性

content string

增量訊息內容。

reasoning_content string

增量思維鏈內容。

function_call object

該值預設為null,請參考tool_calls參數。

audio object

使用 Qwen-Omni 模型時產生的回複。

屬性

data string

增量的 Base64 音頻編碼資料。

expires_at integer

建立請求時的時間戳記。

refusal object

該參數當前固定為null

role string

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

tool_calls array

在發起 Function Calling後,模型產生的工具與入參資訊。

屬性

index integer

當前工具在tool_calls數組中的索引。

id string

本次工具響應的唯一識別碼。

function object

被調用的工具資訊。

屬性

arguments string

增量的入參資訊,所有chunk的arguments拼接後為完整的入參。

由於大模型響應有一定隨機性,輸出的入參資訊可能不符合函數簽名。請在調用前校正參數有效性。

name string

工具名稱,只在第一個chunk中有值。

type string

工具類型,當前只支援function

finish_reason string

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

  • 因觸發輸入參數中的stop參數,或自然停止輸出時為stop

  • 產生未結束時為null

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

  • 需要調用工具而結束為tool_calls

index integer

當前響應在choices數組中的索引。當輸入參數 n 大於1時,需根據本參數進行不同響應對應的完整內容的拼接。

logprobs object

當前對象的機率資訊。

屬性

content array

帶有對數機率資訊的 Token 數組。

屬性

token string

當前 Token。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容,在處理Emoji、中文字元時有協助。

logprob float

當前 Token 的對數機率。傳回值為 null 表示機率值極低。

top_logprobs array

當前 Token 位置最可能的若干個 Token 及其對數機率,元素個數與入參的top_logprobs保持一致。

屬性

token string

當前 Token。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容,在處理Emoji、中文字元時有協助。

logprob float

當前 Token 的對數機率。傳回值為 null 表示機率值極低。

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

輸出 Token 的詳細資料。

屬性

audio_tokens integer

Qwen-Omni 模型輸出的音頻 Token 數。

reasoning_tokens integer

思考過程 Token 數。

text_tokens integer

輸出文本 Token 數。

prompt_tokens_details object

輸入 Token的細粒度分類。

屬性

audio_tokens integer

輸入音訊 Token 數。

視頻檔案中的音頻 Token 數通過本參數返回。

text_tokens integer

輸入文本的 Token 數。

video_tokens integer

輸入視頻(圖片列表形式或視頻檔案)的 Token 數。

image_tokens integer

輸入圖片的 Token 數。

cached_tokens integer

命中緩衝的 Token 數。Context Cache 詳情請參見上下文緩衝

cache_creation object

顯式緩衝建立資訊。

屬性

ephemeral_5m_input_tokens integer

建立顯式緩衝的 Token 數。

cache_creation_input_tokens integer

建立顯式緩衝的 Token 數。

cache_type string

緩衝類型,固定為ephemeral

DashScope

新加坡地區

HTTP 要求地址:

  • 通義千問大語言模型:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation

  • 通義千問VL模型:POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-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 要求地址:

  • 通義千問大語言模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation

  • 通義千問VL模型:POST https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation

SDK 調用無需配置 base_url

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

請求體

文本輸入

Python

import os
import dashscope

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 以上為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
messages = [
    {'role': 'system', 'content': 'You are a helpful assistant.'},
    {'role': 'user', 'content': '你是誰?'}
]
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-plus", # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    messages=messages,
    result_format='message'
    )
print(response)

Java

// 建議dashscope SDK的版本 >= 2.12.0
import java.util.Arrays;
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.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.utils.JsonUtils;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public static GenerationResult callWithMessage() throws ApiException, NoApiKeyException, InputRequiredException {
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        // 以上為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
        Message systemMsg = Message.builder()
                .role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant.")
                .build();
        Message userMsg = Message.builder()
                .role(Role.USER.getValue())
                .content("你是誰?")
                .build();
        GenerationParam param = GenerationParam.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(systemMsg, userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .build();
        return gen.call(param);
    }
    public static void main(String[] args) {
        try {
            GenerationResult result = callWithMessage();
            System.out.println(JsonUtils.toJson(result));
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            // 使用日誌架構記錄異常資訊
            System.err.println("An error occurred while calling the generation service: " + e.getMessage());
        }
        System.exit(0);
    }
}

PHP(HTTP)

<?php
// 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
$url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');

$data = [
    // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    "model" => "qwen-plus",
    "input" => [
        "messages" => [
            [
                "role" => "system",
                "content" => "You are a helpful assistant."
            ],
            [
                "role" => "user",
                "content" => "你是誰?"
            ]
        ]
    ],
    "parameters" => [
        "result_format" => "message"
    ]
];

$jsonData = json_encode($data);

$ch = curl_init($url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonData);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, [
    "Authorization: Bearer $apiKey",
    "Content-Type: application/json"
]);

$response = curl_exec($ch);
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE);

if ($httpCode == 200) {
    echo "Response: " . $response;
} else {
    echo "Error: " . $httpCode . " - " . $response;
}

curl_close($ch);
?>

Node.js(HTTP)

DashScope 未提供 Node.js 環境的 SDK。如需通過 OpenAI Node.js SDK調用,請參考本文的OpenAI章節。

import fetch from 'node-fetch';
// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
const apiKey = process.env.DASHSCOPE_API_KEY;

const data = {
    model: "qwen-plus", // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    input: {
        messages: [
            {
                role: "system",
                content: "You are a helpful assistant."
            },
            {
                role: "user",
                content: "你是誰?"
            }
        ]
    },
    parameters: {
        result_format: "message"
    }
};

fetch('https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation', {
// 以上為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
    method: 'POST',
    headers: {
        'Authorization': `Bearer ${apiKey}`,
        'Content-Type': 'application/json'
    },
    body: JSON.stringify(data)
})
.then(response => response.json())
.then(data => {
    console.log(JSON.stringify(data));
})
.catch(error => {
    console.error('Error:', error);
});

C#(HTTP)

using System.Net.Http.Headers;
using System.Text;

class Program
{
    private static readonly HttpClient httpClient = new HttpClient();

    static async Task Main(string[] args)
    {
        // 若沒有配置環境變數,請用百鍊API Key將下行替換為:string? apiKey = "sk-xxx";
        // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
$apiKey = getenv('DASHSCOPE_API_KEY');
        string? apiKey = Environment.GetEnvironmentVariable("DASHSCOPE_API_KEY");

        if (string.IsNullOrEmpty(apiKey))
        {
            Console.WriteLine("API Key 未設定。請確保環境變數 'DASHSCOPE_API_KEY' 已設定。");
            return;
        }

        // 佈建要求 URL 和內容
        // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
        string url = "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation";
        // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        string jsonContent = @"{
            ""model"": ""qwen-plus"", 
            ""input"": {
                ""messages"": [
                    {
                        ""role"": ""system"",
                        ""content"": ""You are a helpful assistant.""
                    },
                    {
                        ""role"": ""user"",
                        ""content"": ""你是誰?""
                    }
                ]
            },
            ""parameters"": {
                ""result_format"": ""message""
            }
        }";

        // 發送請求並擷取響應
        string result = await SendPostRequestAsync(url, jsonContent, apiKey);

        // 輸出結果
        Console.WriteLine(result);
    }

    private static async Task<string> SendPostRequestAsync(string url, string jsonContent, string apiKey)
    {
        using (var content = new StringContent(jsonContent, Encoding.UTF8, "application/json"))
        {
            // 佈建要求頭
            httpClient.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", apiKey);
            httpClient.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json"));

            // 發送請求並擷取響應
            HttpResponseMessage response = await httpClient.PostAsync(url, content);

            // 處理響應
            if (response.IsSuccessStatusCode)
            {
                return await response.Content.ReadAsStringAsync();
            }
            else
            {
                return $"請求失敗: {response.StatusCode}";
            }
        }
    }
}

Go(HTTP)

DashScope 未提供 Go 的 SDK。如需通過 OpenAI Go SDK調用,請參考本文的OpenAI-Go章節。

package main

import (
	"bytes"
	"encoding/json"
	"fmt"
	"io"
	"log"
	"net/http"
	"os"
)

type Message struct {
	Role    string `json:"role"`
	Content string `json:"content"`
}

type Input struct {
	Messages []Message `json:"messages"`
}

type Parameters struct {
	ResultFormat string `json:"result_format"`
}

type RequestBody struct {
	Model      string     `json:"model"`
	Input      Input      `json:"input"`
	Parameters Parameters `json:"parameters"`
}

func main() {
	// 建立 HTTP 用戶端
	client := &http.Client{}

	// 構建請求體
	requestBody := RequestBody{
		// 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
		Model: "qwen-plus",
		Input: Input{
			Messages: []Message{
				{
					Role:    "system",
					Content: "You are a helpful assistant.",
				},
				{
					Role:    "user",
					Content: "你是誰?",
				},
			},
		},
		Parameters: Parameters{
			ResultFormat: "message",
		},
	}

	jsonData, err := json.Marshal(requestBody)
	if err != nil {
		log.Fatal(err)
	}

	// 建立 POST 請求
	// 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
	req, err := http.NewRequest("POST", "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation", bytes.NewBuffer(jsonData))
	if err != nil {
		log.Fatal(err)
	}

	// 佈建要求頭
	// 若沒有配置環境變數,請用百鍊API Key將下行替換為:apiKey := "sk-xxx"
	// 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
	apiKey := os.Getenv("DASHSCOPE_API_KEY")
	req.Header.Set("Authorization", "Bearer "+apiKey)
	req.Header.Set("Content-Type", "application/json")

	// 發送請求
	resp, err := client.Do(req)
	if err != nil {
		log.Fatal(err)
	}
	defer resp.Body.Close()

	// 讀取響應體
	bodyText, err := io.ReadAll(resp.Body)
	if err != nil {
		log.Fatal(err)
	}

	// 列印響應內容
	fmt.Printf("%s\n", bodyText)
}

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key
以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你是誰?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

流式輸出

相關文檔:流式輸出

文本產生模型

Python

import os
import dashscope

# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [
    {'role':'system','content':'you are a helpful assistant'},
    {'role': 'user','content': '你是誰?'}
]
responses = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    model="qwen-plus",
    messages=messages,
    result_format='message',
    stream=True,
    incremental_output=True
    )
for response in responses:
    print(response)  

Java

import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
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.utils.JsonUtils;
import io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static void handleGenerationResult(GenerationResult message) {
        System.out.println(JsonUtils.toJson(message));
    }
    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) {
        return GenerationParam.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(Arrays.asList(userMsg))
                .resultFormat(GenerationParam.ResultFormat.MESSAGE)
                .incrementalOutput(true)
                .build();
    }
    public static void main(String[] args) {
        try {
            // 以下為新加坡地區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();
            streamCallWithMessage(gen, userMsg);
        } catch (ApiException | NoApiKeyException | InputRequiredException  e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

curl

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

curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--header "X-DashScope-SSE: enable" \
--data '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "user",
                "content": "你是誰?"
            }
        ]
    },
    "parameters": {
        "result_format": "message",
        "incremental_output":true
    }
}'

多模態模型

Python

import os
from dashscope import MultiModalConversation
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/compatible-mode/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'

messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
            {"text": "圖中描繪的是什麼景象?"}
        ]
    }
]

responses = MultiModalConversation.call(
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='qwen3-vl-plus',  #  可按需更換為其它多模態模型,並修改相應的 messages
    messages=messages,
    stream=True,
    incremental_output=True)
    
full_content = ""
print("流式輸出內容為:")
for response in responses:
    if response["output"]["choices"][0]["message"].content:
        print(response.output.choices[0].message.content[0]['text'])
        full_content += response.output.choices[0].message.content[0]['text']
print(f"完整內容為:{full_content}")

Java

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    public static void streamCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        // must create mutable map.
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
                        Collections.singletonMap("text", "圖中描繪的是什麼景象?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen3-vl-plus")  //  可按需更換為其它多模態模型,並修改相應的 messages
                .messages(Arrays.asList(userMessage))
                .incrementalOutput(true)
                .build();
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(item -> {
            try {
                var content = item.getOutput().getChoices().get(0).getMessage().getContent();
                    // 判斷content是否存在且不為空白
                if (content != null &&  !content.isEmpty()) {
                    System.out.println(content.get(0).get("text"));
                    }
            } catch (Exception e){
                System.exit(0);
            }
        });
    }

    public static void main(String[] args) {
        try {
            streamCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

# ======= 重要提示 =======
# 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === 執行時請刪除該注釋 ===

curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-H 'X-DashScope-SSE: enable' \
-d '{
    "model": "qwen3-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
                    {"text": "圖中描繪的是什麼景象?"}
                ]
            }
        ]
    },
    "parameters": {
        "incremental_output": true
    }
}'

映像輸入

關於大模型分析映像的更多用法,請參見視覺理解

Python

import os
import dashscope

# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'  
messages = [
    {
        "role": "user",
        "content": [
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
            {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
            {"text": "這些是什麼?"}
        ]
    }
]
response = dashscope.MultiModalConversation.call(
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 此處以qwen-vl-max為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    model='qwen-vl-max',
    messages=messages
    )
print(response)

Java

// Copyright (c) Alibaba, Inc. and its affiliates.

import java.util.Arrays;
import java.util.Collections;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.JsonUtils;
import com.alibaba.dashscope.utils.Constants;
public class Main {
    static {
     Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";  // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1;
    }
    public static void simpleMultiModalConversationCall()
            throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage userMessage = MultiModalMessage.builder().role(Role.USER.getValue())
                .content(Arrays.asList(
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"),
                        Collections.singletonMap("image", "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"),
                        Collections.singletonMap("text", "這些是什麼?"))).build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此處以qwen-vl-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
                .model("qwen-vl-plus")
                .message(userMessage)
                .build();
        MultiModalConversationResult result = conv.call(param);
        System.out.println(JsonUtils.toJson(result));
    }

    public static void main(String[] args) {
        try {
            simpleMultiModalConversationCall();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key
以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
curl --location 'https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation' \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header 'Content-Type: application/json' \
--data '{
    "model": "qwen-vl-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/tiger.png"},
                    {"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/rabbit.png"},
                    {"text": "這些是什麼?"}
                ]
            }
        ]
    }
}'

視頻輸入

以下為傳入的視訊幀的範例程式碼,關於更多用法(如傳入的視訊檔案),請參見視覺理解

Python

import os
# dashscope版本需要不低於1.20.10
import dashscope
# 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
messages = [{"role": "user",
             "content": [
                  # 若模型屬於Qwen2.5-VL系列且傳入的是映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的
                 {"video":["https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
                           "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
                           "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
                           "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"],
                   "fps":2},
                 {"text": "描述這個視頻的具體過程"}]}]
response = dashscope.MultiModalConversation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model='qwen2.5-vl-72b-instruct',  # 此處以qwen2.5-vl-72b-instruct為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
    messages=messages
)
print(response["output"]["choices"][0]["message"].content[0]["text"])

Java

// DashScope SDK版本需要不低於2.18.3
import java.util.Arrays;
import java.util.Collections;
import java.util.Map;

import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
         // 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
        Constants.baseHttpApiUrl="https://dashscope-intl.aliyuncs.com/api/v1";
    }
    private static final String MODEL_NAME = "qwen2.5-vl-72b-instruct"; // 此處以qwen2.5-vl-72b-instruct為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/models
    public static void videoImageListSample() throws ApiException, NoApiKeyException, UploadFileException {
        MultiModalConversation conv = new MultiModalConversation();
        MultiModalMessage systemMessage = MultiModalMessage.builder()
                .role(Role.SYSTEM.getValue())
                .content(Arrays.asList(Collections.singletonMap("text", "You are a helpful assistant.")))
                .build();
        //  若模型屬於Qwen2.5-VL系列且傳入的是映像列表時,可設定fps參數,表示映像列表是由原視頻每隔 1/fps 秒抽取的
        Map<String, Object> params = Map.of(
                "video", Arrays.asList("https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
                        "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"),
                "fps",2);
        MultiModalMessage userMessage = MultiModalMessage.builder()
                .role(Role.USER.getValue())
                .content(Arrays.asList(
                        params,
                        Collections.singletonMap("text", "描述這個視頻的具體過程")))
                .build();
        MultiModalConversationParam param = MultiModalConversationParam.builder()
                // 若沒有配置環境變數,請用百鍊API Key將下行替換為:.apiKey("sk-xxx")
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model(MODEL_NAME)
                .messages(Arrays.asList(systemMessage, userMessage)).build();
        MultiModalConversationResult result = conv.call(param);
        System.out.print(result.getOutput().getChoices().get(0).getMessage().getContent().get(0).get("text"));
    }
    public static void main(String[] args) {
        try {
            videoImageListSample();
        } catch (ApiException | NoApiKeyException | UploadFileException e) {
            System.out.println(e.getMessage());
        }
        System.exit(0);
    }
}

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key
以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
curl -X POST https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H 'Content-Type: application/json' \
-d '{
  "model": "qwen2.5-vl-72b-instruct",
  "input": {
    "messages": [
      {
        "role": "user",
        "content": [
          {
            "video": [
              "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/xzsgiz/football1.jpg",
              "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/tdescd/football2.jpg",
              "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/zefdja/football3.jpg",
              "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241108/aedbqh/football4.jpg"
            ],
            "fps":2
                 
          },
          {
            "text": "描述這個視頻的具體過程"
          }
        ]
      }
    ]
  }
}'

工具調用

完整的Function Calling流程代碼請參見文本產生模型概述

Python

import os
import dashscope
  # 以下為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
tools = [
    {
        "type": "function",
        "function": {
            "name": "get_current_time",
            "description": "當你想知道現在的時間時非常有用。",
            "parameters": {}
        }
    },
    {
        "type": "function",
        "function": {
            "name": "get_current_weather",
            "description": "當你想查詢指定城市的天氣時非常有用。",
            "parameters": {
                "type": "object",
                "properties": {
                    "location": {
                        "type": "string",
                        "description": "城市或縣區,比如北京市、杭州市、餘杭區等。"
                    }
                }
            },
            "required": [
                "location"
            ]
        }
    }
]
messages = [{"role": "user", "content": "杭州天氣怎麼樣"}]
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
    model='qwen-plus',
    messages=messages,
    tools=tools,
    result_format='message'
)
print(response)

Java

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import com.alibaba.dashscope.aigc.conversation.ConversationParam.ResultFormat;
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.tools.FunctionDefinition;
import com.alibaba.dashscope.tools.ToolFunction;
import com.alibaba.dashscope.utils.JsonUtils;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.github.victools.jsonschema.generator.Option;
import com.github.victools.jsonschema.generator.OptionPreset;
import com.github.victools.jsonschema.generator.SchemaGenerator;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfig;
import com.github.victools.jsonschema.generator.SchemaGeneratorConfigBuilder;
import com.github.victools.jsonschema.generator.SchemaVersion;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import com.alibaba.dashscope.protocol.Protocol;

public class Main {
    public class GetWeatherTool {
        private String location;
        public GetWeatherTool(String location) {
            this.location = location;
        }
        public String call() {
            return location+"今天是晴天";
        }
    }
    public class GetTimeTool {
        public GetTimeTool() {
        }
        public String call() {
            LocalDateTime now = LocalDateTime.now();
            DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
            String currentTime = "目前時間:" + now.format(formatter) + "。";
            return currentTime;
        }
    }
    public static void SelectTool()
            throws NoApiKeyException, ApiException, InputRequiredException {
        SchemaGeneratorConfigBuilder configBuilder =
                new SchemaGeneratorConfigBuilder(SchemaVersion.DRAFT_2020_12, OptionPreset.PLAIN_JSON);
        SchemaGeneratorConfig config = configBuilder.with(Option.EXTRA_OPEN_API_FORMAT_VALUES)
                .without(Option.FLATTENED_ENUMS_FROM_TOSTRING).build();
        SchemaGenerator generator = new SchemaGenerator(config);
        ObjectNode jsonSchema_weather = generator.generateSchema(GetWeatherTool.class);
        ObjectNode jsonSchema_time = generator.generateSchema(GetTimeTool.class);
        FunctionDefinition fdWeather = FunctionDefinition.builder().name("get_current_weather").description("擷取指定地區的天氣")
                .parameters(JsonUtils.parseString(jsonSchema_weather.toString()).getAsJsonObject()).build();
        FunctionDefinition fdTime = FunctionDefinition.builder().name("get_current_time").description("擷取當前時刻的時間")
                .parameters(JsonUtils.parseString(jsonSchema_time.toString()).getAsJsonObject()).build();
        Message systemMsg = Message.builder().role(Role.SYSTEM.getValue())
                .content("You are a helpful assistant. When asked a question, use tools wherever possible.")
                .build();
        Message userMsg = Message.builder().role(Role.USER.getValue()).content("杭州天氣").build();
        List<Message> messages = new ArrayList<>();
        messages.addAll(Arrays.asList(systemMsg, userMsg));
        GenerationParam param = GenerationParam.builder()
                // 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                // 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
                .model("qwen-plus")
                .messages(messages)
                .resultFormat(ResultFormat.MESSAGE)
                .tools(Arrays.asList(
                        ToolFunction.builder().function(fdWeather).build(),
                        ToolFunction.builder().function(fdTime).build()))
                .build();
        Generation gen = new Generation(Protocol.HTTP.getValue(), "https://dashscope-intl.aliyuncs.com/api/v1");
        // 以上為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
        GenerationResult result = gen.call(param);
        System.out.println(JsonUtils.toJson(result));
    }
    public static void main(String[] args) {
        try {
            SelectTool();
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            System.out.println(String.format("Exception %s", e.getMessage()));
        }
        System.exit(0);
    }
}

curl

新加坡和北京地區的API Key不同,擷取與配置 API Key
以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
curl --location "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-plus",
    "input": {
        "messages": [{
            "role": "user",
            "content": "杭州天氣怎麼樣"
        }]
    },
    "parameters": {
        "result_format": "message",
        "tools": [{
            "type": "function",
            "function": {
                "name": "get_current_time",
                "description": "當你想知道現在的時間時非常有用。",
                "parameters": {}
            }
        },{
            "type": "function",
            "function": {
                "name": "get_current_weather",
                "description": "當你想查詢指定城市的天氣時非常有用。",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "location": {
                            "type": "string",
                            "description": "城市或縣區,比如北京市、杭州市、餘杭區等。"
                        }
                    }
                },
                "required": ["location"]
            }
        }]
    }
}'

非同步呼叫

# 您的Dashscope Python SDK版本需要不低於 1.19.0。
import asyncio
import platform
import os
import dashscope
from dashscope.aigc.generation import AioGeneration

dashscope.base_http_api_url = 'https://dashscope-intl.aliyuncs.com/api/v1'
# 以上為新加坡地區base_url,若使用北京地區的模型,需將base_url替換為:https://dashscope.aliyuncs.com/api/v1
async def main():
    response = await AioGeneration.call(
        # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
        # 新加坡和北京地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
        api_key=os.getenv('DASHSCOPE_API_KEY'),
        # 此處以qwen-plus為例,可按需更換模型名稱。模型列表:https://www.alibabacloud.com/help/zh/model-studio/getting-started/models
        model="qwen-plus",
        messages=[{"role": "user", "content": "你是誰"}],
        result_format="message",
    )
    print(response)

if platform.system() == "Windows":
    asyncio.set_event_loop_policy(asyncio.WindowsSelectorEventLoopPolicy())
asyncio.run(main())

文檔理解

Python

import os
import dashscope

# 當前僅北京地區可調用qwen-long-latest模型
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
messages = [
        {'role': 'system', 'content': 'you are a helpful assisstant'},
        # 請將 '{FILE_ID}'替換為您實際對話情境所使用的 file-id
        {'role':'system','content':f'fileid://{FILE_ID}'},
        {'role': 'user', 'content': '這篇文章講了什麼'}]
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-long-latest",
    messages=messages,
    result_format='message'
)
print(response)

Java

import os
import dashscope

# 當前僅北京地區可調用qwen-long-latest模型
dashscope.base_http_api_url = 'https://dashscope.aliyuncs.com/api/v1'
messages = [
        {'role': 'system', 'content': 'you are a helpful assisstant'},
        # 請將 '{FILE_ID}'替換為您實際對話情境所使用的 file-id
        {'role':'system','content':f'fileid://{FILE_ID}'},
        {'role': 'user', 'content': '這篇文章講了什麼'}]
response = dashscope.Generation.call(
    # 若沒有配置環境變數,請用百鍊API Key將下行替換為:api_key="sk-xxx"
    api_key=os.getenv('DASHSCOPE_API_KEY'),
    model="qwen-long-latest",
    messages=messages,
    result_format='message'
)
print(response)

curl

當前僅北京地區支援調用文檔理解模型
請將 {FILE_ID}替換為您實際對話情境所使用的 file-id
curl --location "https://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
--header "Authorization: Bearer $DASHSCOPE_API_KEY" \
--header "Content-Type: application/json" \
--data '{
    "model": "qwen-long-latest",
    "input":{
        "messages":[      
            {
                "role": "system",
                "content": "You are a helpful assistant."
            },
            {
                "role": "system",
                "content": "fileid://{FILE_ID}"
            },
            {
                "role": "user",
                "content": "這篇文章講了什嗎?"
            }
        ]
    },
    "parameters": {
        "result_format": "message"
    }
}'

model string (必選)

模型名稱。

支援的模型:Qwen 大語言模型(商業版、開源版)、Qwen-VL、Qwen-Coder。

具體模型名稱和計費,請參見模型列表

messages array (必選)

傳遞給大模型的上下文,按對話順序排列。

通過HTTP調用時,請將messages 放入 input 對象中。

訊息類型

System Message object(可選)

系統訊息,用於設定大模型的角色、語氣、任務目標或約束條件等。一般放在messages數組的第一位。

QwQ模型不建議設定 System Message,QVQ 模型設定 System Message不會生效。

屬性

content string(必選)

訊息內容。

role string (必選)

系統訊息的角色,固定為system

User Message object(必選)

使用者訊息,用於向模型傳遞問題、指令或上下文等。

屬性

content string 或 array(必選)

訊息內容。若輸入只有文本,則為 string 類型;若輸入包含映像等多模態資料,或啟用顯式緩衝,則為 array 類型。

屬性

text string(必選)

輸入的文本。

image string(可選)

指定用於圖片理解的影像檔,映像支援以下三種方式傳入:

  • 公網 URL:公網可訪問的映像連結

  • 圖片的 Base 64 編碼,格式為 data:image/<format>;base64,<data>

  • 本地檔案:本地檔案的絕對路徑

適用模型:Qwen-VLQVQ

樣本值:{"image":"https://xxxx.jpeg"}

video array 或 string(可選)

使用Qwen-VL 模型QVQ模型傳入的視頻。

  • 若傳入映像列表,則為array類型;

  • 若傳入的視訊檔案,則為string類型

傳入本地檔案請參見本地檔案(Qwen-VL)本地檔案(QVQ)

樣本值:

  • 映像列表:{"video":["https://xx1.jpg",...,"https://xxn.jpg"]}

  • 視頻檔案:{"video":"https://xxx.mp4"}

fps float (可選)

每秒抽幀數。取值範圍為 (0.1, 10),預設值為2.0。

有兩個功能:

  • 輸入視頻檔案時,控制抽幀頻率,每 秒抽取一幀。

    適用於Qwen-VL 模型QVQ模型
  • 告知模型相鄰幀之間的時間間隔,協助其更好地理解視頻的時間動態。同時適用於輸入視頻檔案與映像列表時。該功能同時可使用視訊檔案和映像列表輸入,適用於事件時間定位或分段內容摘要等情境。

    支援Qwen2.5-VLQwen3-VL模型與QVQ模型。

樣本值如下:

  • 映像列表傳入:{"video":["https://xx1.jpg",...,"https://xxn.jpg"],"fps":2}

  • 視頻檔案傳入:{"video": "https://xx1.mp4","fps":2}

較大的fps適合高速運動的情境(如體育賽事、動作電影等),較小的fps適合長視頻或內容偏靜態情境。

OpenAI 相容協議不支援設定該值。視頻檔案預設每間隔0.5秒抽取一幀,映像列表預設是以每隔0.5秒從視頻中抽取出來的。

min_pixels integer (可選)

設定輸入映像或視訊框架的最小像素閾值。當輸入映像或視訊框架的像素小於min_pixels時,會將其進行放大,直到總像素高於min_pixels

  • 輸入映像:

    • 適用模型:QVQ、Qwen-VL模型支援

    • 取值範圍:如下所示

      min_pixels 取值範圍

      • Qwen3-VL:預設值和最小值均為65536

      • qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815:預設值和最小值均為4096

      • QVQ 及其他 Qwen2.5-VL 模型:預設值和最小值均為3136

    • 樣本值:{"image":"https://xxxx.jpg", "min_pixels": 65536}

  • 輸入視頻檔案或映像列表:

    • 適用模型:僅qwen3-vl-plusqwen3-vl-plus-2025-09-23模型支援

    • 取值範圍:預設值為65536,最小值為4096

    • 樣本值:

      • 輸入視頻檔案時:{"video":"https://xxxx.mp4","min_pixels": 65536}

      • 輸入映像列表時:{"video":["https://xx1.jpg",...,"https://xxn.jpg"],"min_pixels": 65536}

OpenAI 相容協議僅支援在傳入映像時設定該參數。

max_pixels integer (可選)

用於設定輸入映像或視訊框架的最大像素閾值。當輸入映像或視頻的像素在[min_pixels, max_pixels]區間內時,模型會按原圖進行識別。當輸入映像像素大於max_pixels時,會將映像進行縮小,直到總像素低於max_pixels

  • 輸入映像:

    • 適用模型:QVQ、Qwen-VL 模型支援

    • 取值範圍:如下所示

      max_pixels 取值範圍

      max_pixels的取值與是否開啟vl_high_resolution_images參數有關。

      • vl_high_resolution_imagesFalse時:

        • Qwen3-VL:預設值為2621440,最大值為:16777216

        • qwen-vl-maxqwen-vl-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plusqwen-vl-plus-0815:預設值為1310720,最大值為:16777216

        • QVQ及其他Qwen2.5-VL模型:預設值為1003520 ,最大值為12845056

      • vl_high_resolution_imagesTrue時:

        • Qwen3-VLqwen-vl-max-0813qwen-vl-plus-0815max_pixels無效,輸入映像的最大像素固定為16777216

        • QVQ及其他Qwen2.5-VL模型:max_pixels無效,輸入映像的最大像素固定為12845056

    • 樣本值:{"image":"https://xxxx.jpg", "max_pixels": 8388608}

  • 輸入視頻檔案或映像列表:

    • 適用模型:僅qwen3-vl-plusqwen3-vl-plus-2025-09-23模型支援

    • 取值範圍:預設值為655360,最大值為2048000

    • 樣本值:

      • 輸入視頻檔案時:{"video":"https://xxxx.mp4","max_pixels": 655360}

      • 輸入映像列表時:{"video":["https://xx1.jpg",...,"https://xxn.jpg"],"max_pixels": 655360}

OpenAI 相容協議僅支援在傳入映像時設定該參數。

total_pixels integer (可選)

用於限制從視頻中抽取的所有幀的總像素(單幀映像像素 × 總幀數)。

如果視頻總像素超過此限制,系統將對視訊框架進行縮放,但仍會確保單幀映像的像素值在 [min_pixels, max_pixels] 範圍內。

  • 適用模型:僅qwen3-vl-plusqwen3-vl-plus-2025-09-23模型支援。

  • 取值說明:預設值和最小值均為134217728,該值對應 131072 個映像 Token(每 32×32 像素對應 1 個映像 Token)。

  • 樣本值:

    • 輸入視頻檔案時:{"video":"https://xxxx.mp4","total_pixels": 134217728}

    • 輸入映像列表時:{"video":["https://xx1.jpg",...,"https://xxn.jpg"],"total_pixels": 134217728}

對於抽幀數量較多的長視頻,可適當降低此值以減少Token消耗和處理時間,但這可能會導致映像細節丟失。

cache_control object (可選)

僅支援顯式緩衝的模型支援,用於開啟顯式緩衝。

屬性

type string(必選)

固定為ephemeral

role string (必選)

使用者訊息的角色,固定為user

Assistant Message object (可選)

模型對使用者訊息的回複。

屬性

content string (可選)

訊息內容。僅當助手訊息中指定tool_calls參數時非必選。

role string (必選)

固定為assistant

partial boolean (可選)

是否開啟首碼續寫。相關文檔:首碼續寫

支援的模型

  • 通義千問Max 系列

    qwen3-max、qwen3-max-2025-09-23、qwen3-max-preview(非思考模式)、qwen-max、qwen-max-latest、qwen-max-2025-01-25及之後的快照模型

  • 通義千問Plus 系列(非思考模式)

    qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25及之後的快照模型

  • 通義千問Flash 系列(非思考模式)

    qwen-flash、qwen-flash-2025-07-28及之後的快照模型

  • 通義千問Coder 系列

    qwen3-coder-plus、qwen3-coder-flash、qwen3-coder-480b-a35b-instruct、qwen3-coder-30b-a3b-instruct

  • 通義千問VL 系列

    • qwen3-vl-plus 系列(非思考模式)

      qwen3-vl-plus、qwen3-vl-plus-2025-09-23及之後的快照模型

    • qwen3-vl-flash 系列(非思考模式)

      qwen3-vl-flash、qwen3-vl-flash-2025-10-15及之後的快照模型

    • qwen-vl-max 系列

      qwen-vl-max、qwen-vl-max-latest、qwen-vl-max-2025-04-08及之後的快照模型

    • qwen-vl-plus 系列

      qwen-vl-plus、qwen-vl-plus-latest、qwen-vl-plus-2025-01-25及之後的快照模型

  • 通義千問Turbo 系列(非思考模式)

    qwen-turbo、qwen-turbo-latest、qwen-turbo-2024-11-01及之後的快照模型

  • 通義千問開源系列

    Qwen3 開源模型(非思考模式)、Qwen2.5系列的文本模型、Qwen3-VL開源模型(非思考模式)

tool_calls array (可選)

發起 Function Calling 後,返回的工具與入參資訊,包含一個或多個對象。由上一輪模型響應的tool_calls欄位獲得。

屬性

id string

工具響應的ID。

type string

工具類型,當前只支援設為function

function object

工具與入參資訊。

屬性

name string

工具名稱。

arguments string

入參資訊,為JSON格式字串。

index integer

當前工具資訊在tool_calls數組中的索引。

Tool Message object(可選)

工具的輸出資訊。

屬性

content string (必選)

工具函數的輸出內容,必須為字串格式。

role string (必選)

固定為tool

tool_call_id string (可選)

發起 Function Calling 後返回的 id,可以通過response.output.choices[0].message.tool_calls[$index]["id"]擷取,用於標記 Tool Message 對應的工具。

temperature float (可選)

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

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

取值範圍: [0, 2)

通過HTTP調用時,請將 temperature 放入 parameters 對象中。
不建議修改QVQ模型的預設 temperature 值。

top_p float (可選)

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

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

取值範圍:(0,1.0]。

top_p預設值

Qwen3(非思考模式)、Qwen3-Instruct系列、Qwen3-Coder系列、qwen-max系列、qwen-plus系列(非思考模式)、qwen-flash系列(非思考模式)、qwen-turbo系列(非思考模式)、qwen開源系列、qwen-vl-max-2025-08-13、Qwen3-VL(非思考模式):0.8;

:0.01;

qwen-vl-plus系列、qwen-vl-max、qwen-vl-max-latest、qwen-vl-max-2025-04-08、qwen2.5-vl-3b-instruct、qwen2.5-vl-7b-instruct、qwen2.5-vl-32b-instruct、qwen2.5-vl-72b-instruct:0.001;

QVQ系列、qwen-vl-plus-2025-07-10、qwen-vl-plus-2025-08-15 :0.5;

qwen3-max-preview(思考模式)、Qwen3-Omni-Flash系列:1.0;

Qwen3(思考模式)、Qwen3-VL(思考模式)、Qwen3-Thinking、QwQ 系列、Qwen3-Omni-Captioner:0.95

Java SDK中為topP通過HTTP調用時,請將 top_p 放入 parameters 對象中。
不建議修改QVQ模型的預設 top_p 值。

top_k integer (可選)

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

取值需要大於或等於0。

top_k預設值

QVQ系列、qwen-vl-plus-2025-07-10、qwen-vl-plus-2025-08-15:10;

QwQ 系列:40;

其餘qwen-vl-plus系列、qwen-vl-max-2025-08-13之前的模型、qwen2.5-omni-7b:1;

Qwen3-Omni-Flash系列:50

其餘模型均為20;

Java SDK中為topK通過HTTP調用時,請將 top_k 放入 parameters 對象中。
不建議修改QVQ模型的預設 top_k 值。

enable_thinking boolean (可選)

使用混合思考模型時,是否開啟思考模式,適用於 Qwen3 、Qwen3-VL模型。相關文檔:深度思考

可選值:

  • true:開啟

    開啟後,思考內容將通過reasoning_content欄位返回。
  • false:不開啟

不同模型的預設值:支援的模型

Java SDK 為enableThinking;通過HTTP調用時,請將 enable_thinking 放入 parameters 對象中。

thinking_budget integer (可選)

思考過程的最大長度。適用於Qwen3-VL、Qwen3 的商業版與開源版模型。相關文檔:限制思考長度

預設值為模型最大思維鏈長度,請參見:模型列表

Java SDK 為 thinkingBudget。通過HTTP調用時,請將 thinking_budget 放入 parameters 對象中。
預設值為模型最大思維鏈長度。

enable_code_interpreter boolean (可選)預設值為 false

是否開啟代碼解譯器功能。僅適用于思考模式下的 qwen3-max-preview。相關文檔:代碼解譯器

可選值:

  • true:開啟

  • false:不開啟

不支援 Java SDK。通過HTTP調用時,請將 enable_code_interpreter 放入 parameters 對象中。

repetition_penalty float (可選)

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

Java SDK中為repetitionPenalty通過HTTP調用時,請將 repetition_penalty 放入 parameters 對象中。
使用qwen-vl-plus_2025-01-25模型進行文字提取時,建議設定repetition_penalty為1.0。
不建議修改QVQ模型的預設 repetition_penalty 值。

presence_penalty float (可選)

控制模型產生文本時的內容重複度。

取值範圍:[-2.0, 2.0]。正值降低重複度,負值增加重複度。

在創意寫作或頭腦風暴等需要多樣性、趣味性或創造力的情境中,建議調高該值;在技術文檔或正式文本等強調一致性與術語準確性的情境中,建議調低該值。

presence_penalty預設值

qwen3-max-preview(思考模式)、Qwen3(非思考模式)、Qwen3-Instruct系列、qwen3-0.6b/1.7b/4b(思考模式)、QVQ系列、qwen-max、qwen-max-latest、qwen-max-latestqwen2.5-vl系列、qwen-vl-max系列、qwen-vl-plus、Qwen3-VL(非思考):1.5;

qwen-vl-plus-latest、qwen-vl-plus-2025-08-15:1.2

qwen-vl-plus-2025-01-25:1.0;

qwen3-8b/14b/32b/30b-a3b/235b-a22b(思考模式)、qwen-plus/qwen-plus-latest/2025-04-28(思考模式)、qwen-turbo/qwen-turbo/2025-04-28(思考模式):0.5;

其餘均為0.0。

原理介紹

如果參數值是正數,模型將對目前文本中已存在的Token施加一個懲罰值(懲罰值與文本出現的次數無關),減少這些Token重複出現的幾率,從而減少內容重複度,增加用詞多樣性。

樣本

提示詞:把這句話翻譯成中文“This movie is good. The plot is good, the acting is good, the music is good, and overall, the whole movie is just good. It is really good, in fact. The plot is so good, and the acting is so good, and the music is so good.”

參數值為2.0:這部電影很好。劇情很棒,演技棒,音樂也非常好聽,總的來說,整部電影都好得不得了。實際上它真的很優秀。劇情非常精彩,演技出色,音樂也是那麼的動聽。

參數值為0.0:這部電影很好。劇情好,演技好,音樂也好,總的來說,整部電影都很好。事實上,它真的很棒。劇情非常好,演技也非常出色,音樂也同樣優秀。

參數值為-2.0:這部電影很好。情節很好,演技很好,音樂也很好,總的來說,整部電影都很好。實際上,它真的很棒。情節非常好,演技也非常好,音樂也非常好。

使用qwen-vl-plus-2025-01-25模型進行文字提取時,建議設定presence_penalty為1.5。
不建議修改QVQ模型的預設presence_penalty值。
Java SDK不支援設定該參數通過HTTP調用時,請將 presence_penalty 放入 parameters 對象中。

vl_high_resolution_images boolean (可選)預設值為false

是否將輸入映像的像素上限提升至 16384 Token 對應的像素值。相關文檔:處理高解析度映像

  • vl_high_resolution_images:true,使用固定解析度策略,忽略 max_pixels 設定,超過此解析度時會將映像總像素縮小至此上限內。

    點擊查看各模型像素上限

    vl_high_resolution_imagesTrue時,不同模型像素上限不同:

    • Qwen3-VL系列qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815模型:16777216(每Token對應32*32像素,即16384*32*32

    • QVQ系列、其他Qwen2.5-VL系列模型:12845056(每Token對應28*28像素,即 16384*28*28

  • vl_high_resolution_imagesfalse,實際解析度由 max_pixels 與預設上限共同決定,取二者計算結果的最大值。超過此像素上限時會將映像縮小至此上限內。

    點擊查看各模型的預設像素上限

    vl_high_resolution_imagesfalse時,不同模型預設像素上限不同:

    • Qwen3-VL系列2621440(2560*32*32,即預設Token上限為2560)

    • qwen-vl-maxqwen-vl-max-latestqwen-vl-max-0813qwen-vl-plusqwen-vl-plus-latestqwen-vl-plus-0815模型:1310720(1280*32*32,即預設Token上限為1280)

    • QVQ系列、其他Qwen2.5-VL系列模型:1003520(1280*28*28,即預設Token上限為1280)

Java SDK 為 vlHighResolutionImages(需要的最低版本為2.20.8通過HTTP調用時,請將 vl_high_resolution_images 放入 parameters 對象中。

vl_enable_image_hw_output boolean (可選)預設值為 false

是否返回映像縮放後的尺寸。模型會對輸入的映像進行縮放處理,配置為 True 時會返回映像縮放後的高度和寬度,開啟流式輸出時,該資訊在最後一個資料區塊(chunk)中返回。支援Qwen-VL模型

Java SDK中為 vlEnableImageHwOutput,Java SDK最低版本為2.20.8通過HTTP調用時,請將 vl_enable_image_hw_output 放入 parameters 對象中。

max_input_tokens integer (可選)

允許輸入的最大 Token 長度。目前僅支援qwen-plus-0728/latest模型。

  • qwen-plus-latest 預設值:129,024

    後續預設值可能調整至1,000,000。
  • qwen-plus-2025-07-28 預設值:1,000,000

Java SDK 暫不支援該參數。通過HTTP調用時,請將 max_input_tokens 放入 parameters 對象中。

max_tokens integer (可選)

用於限制模型輸出的最大 Token 數。若產生內容超過此值,產生將提前停止,且返回的finish_reasonlength

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

適用於需控制輸出長度的情境,如產生摘要、關鍵詞,或用於降低成本、縮短回應時間。

觸發 max_tokens 時,響應的 finish_reason 欄位為 length

max_tokens不限制思考模型思維鏈的長度。
Java SDK中為maxTokens(模型為通義千問VL時,Java SDK中為maxLength,在 2.18.4 版本之後支援也設定為 maxTokens)通過HTTP調用時,請將 max_tokens 放入 parameters 對象中。

seed integer (可選)

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

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

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

stream boolean (可選) 預設值為false

是否流式輸出回複。參數值:

  • false:模型產生完所有內容後一次性返回結果。

  • true:邊產生邊輸出,即每產生一部分內容就立即輸出一個片段(chunk)。

該參數僅支援Python SDK。通過Java SDK實現流式輸出請通過streamCall介面調用;通過HTTP實現流式輸出請在Header中指定X-DashScope-SSEenable
Qwen3商業版(思考模式)、Qwen3開源版、QwQ、QVQ只支援流式輸出。

incremental_output boolean (可選)預設為false(Qwen3-Max、Qwen3-VL、Qwen3 開源版QwQQVQ模型預設值為 true

在流式輸出模式下是否開啟增量輸出。推薦您優先設定為true

參數值:

  • false:每次輸出為當前已經產生的整個序列,最後一次輸出為產生的完整結果。

    I
    I like
    I like apple
    I like apple.
  • true(推薦):增量輸出,即後續輸出內容不包含已輸出的內容。您需要即時地逐個讀取這些片段以獲得完整的結果。

    I
    like
    apple
    .
Java SDK中為incrementalOutput通過HTTP調用時,請將 incremental_output 放入 parameters 對象中。
QwQ 模型與思考模式下的 Qwen3 模型只支援設定為 true。由於 Qwen3 商業版模型預設值為false,您需要在思考模式下手動設定為 true
Qwen3 開源版模型不支援設定為 false

response_format object (可選) 預設值為{"type": "text"}

返回內容的格式。可選值:{"type": "text"}{"type": "json_object"}。設定為{"type": "json_object"}時會輸出標準格式的JSON字串。相關文檔:結構化輸出

如果指定為{"type": "json_object"},需同時在提示詞中指引模型輸出JSON格式,如:“請按照json格式輸出”,否則會報錯。
Java SDK 中為 responseFormat。通過HTTP調用時,請將 response_format 放入 parameters 對象中。

支援的模型

  • 文本產生模型

    • 通義千問Max 系列:qwen3-max、qwen3-max-2025-09-23、qwen3-max-preview(非思考模式)qwen-max、qwen-max-latest、qwen-max-2025-01-25 及之後的快照模型

    • 通義千問Plus 系列(非思考模式):qwen-plus、qwen-plus-latest、qwen-plus-2025-01-25及之後的快照模型

    • 通義千問Flash 系列(非思考模式):qwen-flash、qwen-flash-2025-07-28及之後的快照模型

    • 通義千問Turbo 系列(非思考模式):qwen-turbo、qwen-turbo-latest、qwen-turbo-2024-11-01及之後的快照模型

    • 通義千問Coder 系列:qwen3-coder-plus、qwen3-coder-plus-2025-07-22、qwen3-coder-flash、qwen3-coder-flash-2025-07-28

    • 通義千問Long 系列:qwen-long-latest、qwen-long-2025-01-25

  • 文本產生開源模型

    • Qwen3(非思考模式)

    • Qwen3-Coder

    • Qwen2.5 系列的文本模型(不含math與coder模型)

  • 多模態模型

    • 通義千問3-VL-Plus 系列(非思考模式):qwen3-vl-plus、qwen3-vl-plus-2025-09-23及之後的快照模型

    • 通義千問3-VL-Flash 系列(非思考模式):qwen3-vl-flash、qwen3-vl-flash-2025-10-15及之後的快照模型

    • 通義千問VL-Max 系列:qwen-vl-max(不包括最新版與快照版模型)

    • 通義千問VL-Plus 系列:qwen-vl-plus(不包括最新版與快照版模型)

  • 多模態開源模型

    • Qwen3-VL(非思考模式)

說明

思考模式的模型暫不支援結構化輸出功能。

result_format string (可選) 預設為text(Qwen3-Max、Qwen3-VL、QwQ 模型、Qwen3 開源模型(除了qwen3-next-80b-a3b-instruct)預設值為 message)

返回資料的格式。推薦您優先設定為message,可以更方便地進行多輪對話

平台後續將統一調整預設值為message
Java SDK中為resultFormat通過HTTP調用時,請將 result_format 放入 parameters 對象中。
模型為通義千問VL/QVQ時,設定text不生效。
Qwen3-Max、Qwen3-VL、思考模式下的 Qwen3 模型只能設定為message,由於 Qwen3 商業版模型預設值為text,您需要將其設定為message
如果您使用 Java SDK 調用Qwen3 開源模型,並且傳入了 text,依然會以 message格式進行返回。

logprobs boolean (可選)預設值為 false

是否返回輸出 Token 的對數機率,可選值:

  • true

    返回

  • false

    不返回

支援以下模型:

  • qwen-plus系列的快照模型(不包含主線模型)

  • qwen-turbo 系列的快照模型(不包含主線模型)

  • Qwen3 開源模型

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

top_logprobs integer (可選)預設值為0

指定在每一步產生時,返回模型最大機率的候選 Token 個數。

取值範圍:[0,5]

僅當 logprobstrue 時生效。

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

n integer (可選) 預設值為1

產生響應的個數,取值範圍是1-4。對於需要產生多個響應的情境(如創意寫作、廣告文案等),可以設定較大的 n 值。

當前僅支援 qwen-plus、 Qwen3(非思考模式) 模型,且在傳入 tools 參數時固定為1。
設定較大的 n 值不會增加輸入 Token 消耗,會增加輸出 Token 的消耗。
通過HTTP調用時,請將 n 放入 parameters 對象中。

stop string 或 array (可選)

用於指定停止詞。當模型產生的文本中出現stop 指定的字串或token_id時,產生將立即終止。

可傳入敏感詞以控制模型的輸出。

stop為數組時,不可將token_id和字串同時作為元素輸入,比如不可以指定為["你好",104307]
通過HTTP調用時,請將 stop 放入 parameters 對象中。

tools array (可選)

包含一個或多個工具對象的數組,供模型在 Function Calling 中調用。相關文檔:Function Calling

使用 tools 時,必須將result_format設為message

發起 Function Calling,或提交工具執行結果時,都必須設定tools參數。

屬性

type string (必選)

工具類型,當前僅支援function

function object (必選)

屬性

name string (必選)

工具函數的名稱,必須是字母、數字,可以包含底線和短劃線,最大長度為64。

description string (必選)

工具函數的描述,供模型選擇何時以及如何調用工具函數。

parameters objcet (必選)

工具的參數描述,需要是一個合法的JSON Schema。JSON Schema的描述可以見連結。如果parameters參數為空白,表示function沒有入參。

通過HTTP調用時,請將 tools 放入 parameters 對象中。暫時不支援qwen-vl系列模型。

tool_choice string 或 object (可選)預設值為 auto

工具選擇策略。若需對某類問題強制指定工具調用方式(例如始終使用某工具或禁用所有工具),可設定此參數。

  • auto

    大模型自主選擇工具策略;

  • none

    若在特定請求中希望臨時禁用工具調用,可設定tool_choice參數為none

  • {"type": "function", "function": {"name": "the_function_to_call"}}

    若希望強制調用某個工具,可設定tool_choice參數為{"type": "function", "function": {"name": "the_function_to_call"}},其中the_function_to_call是指定的工具函數名稱。

    思考模式的模型不支援強制調用某個工具。
Java SDK中為toolChoice通過HTTP調用時,請將 tool_choice 放入 parameters 對象中。

parallel_tool_calls boolean (可選)預設值為 false

是否開啟並行工具調用。

可選值:

  • true:開啟

  • false:不開啟。

並行工具調用詳情請參見:並行工具調用

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

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

{
  "status_code": 200,
  "request_id": "902fee3b-f7f0-9a8c-96a1-6b4ea25af114",
  "code": "",
  "message": "",
  "output": {
    "text": null,
    "finish_reason": null,
    "choices": [
      {
        "finish_reason": "stop",
        "message": {
          "role": "assistant",
          "content": "我是阿里雲開發的一款超大規模語言模型,我叫通義千問。"
        }
      }
    ]
  },
  "usage": {
    "input_tokens": 22,
    "output_tokens": 17,
    "total_tokens": 39
  }
}

status_code string

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

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

request_id string

本次調用的唯一識別碼。

Java SDK返回參數為requestId。

code string

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

只有Python SDK返回該參數。

output object

調用結果資訊。

屬性

text string

模型產生的回複。當設定輸入參數result_formattext時將回複內容返回到該欄位。

finish_reason string

當設定輸入參數result_formattext時該參數不為空白。

有四種情況:

  • 正在產生時為null;

  • 因模型輸出自然結束,或觸發輸入參數中的stop條件而結束時為stop;

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

  • 因發生工具調用為tool_calls。

choices array

模型的輸出資訊。當result_format為message時返回choices參數。

屬性

finish_reason string

有四種情況:

  • 正在產生時為null;

  • 因模型輸出自然結束,或觸發輸入參數中的stop條件而結束時為stop;

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

  • 因發生工具調用為tool_calls。

message object

模型輸出的訊息對象。

屬性

role string

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

content string或array

輸出訊息的內容。當使用qwen-vl或qwen-audio系列模型時為array,其餘情況為string

如果發起Function Calling,則該值為空白。

屬性

text string

當使用qwen-vl或qwen-audio系列模型時,輸出訊息的內容。

image_hw array

當Qwen-VL系列模型啟用 vl_enable_image_hw_output 參數時,有兩種情況:

  • 映像輸入:返回映像的高度和高度(數值單位:像素)

  • 視頻輸入:返回空數組

reasoning_content string

模型的深度思考內容。

tool_calls array

若模型需要調用工具,則會產生tool_calls參數。

屬性

function object

調用工具的名稱,以及輸入參數。

屬性

name string

調用工具的名稱

arguments string

需要輸入到工具中的參數,為JSON字串。

由於大模型響應有一定隨機性,輸出的JSON字串並不總滿足於您的函數,建議您在將參數輸入函數前進行參數的有效性校正。

index integer

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

id string

本次工具響應的ID。

type string

工具類型,固定為function

logprobs object

當前 choices 對象的機率資訊。

屬性

content array

帶有對數機率資訊的 Token 數組。

屬性

token string

當前 Token。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容,在處理Emoji、中文字元時有協助。

logprob float

當前 Token 的對數機率。傳回值為 null 表示機率值極低。

top_logprobs array

當前 Token 位置最可能的若干個 Token 及其對數機率,元素個數與入參的top_logprobs保持一致。

屬性

token string

當前 Token。

bytes array

當前 Token 的 UTF‑8 原始位元組列表,用於精確還原輸出內容,在處理Emoji、中文字元時有協助。

logprob float

當前 Token 的對數機率。傳回值為 null 表示機率值極低。

usage map

本次chat請求使用的Token資訊。

屬性

input_tokens integer

使用者輸入內容轉換成Token後的長度。

output_tokens integer

模型輸出內容轉換成Token後的長度。

input_tokens_details integer

使用Qwen-VL 模型QVQ模型時,輸入內容轉換成Token後的長度詳情。

屬性

text_tokens integer

使用Qwen-VL 模型QVQ模型時,為輸入的文本轉換為Token後的長度。

image_tokens integer

輸入的映像轉換為Token後的長度。

video_tokens integer

輸入的視頻檔案或映像列錶轉換為Token後的長度。

total_tokens integer

當輸入為純文字時返回該欄位,為input_tokensoutput_tokens之和

image_tokens integer

輸入內容包含image時返回該欄位。為使用者輸入圖片內容轉換成Token後的長度。

video_tokens integer

輸入內容包含video時返回該欄位。為使用者輸入視頻內容轉換成Token後的長度。

audio_tokens integer

輸入內容包含audio時返回該欄位。為使用者輸入音頻內容轉換成Token後的長度。

output_tokens_details integer

輸出內容轉換成 Token後的長度詳情。

屬性

text_tokens integer

輸出的文本轉換為Token後的長度。

reasoning_tokens integer

Qwen3 模型思考過程轉換為Token後的長度。

prompt_tokens_details object

輸入 Token 的細粒度分類。

屬性

cached_tokens integer

命中 Cache 的 Token 數。Context Cache 詳情請參見上下文緩衝

cache_creation object

顯式緩衝建立資訊。

屬性

ephemeral_5m_input_tokens integer

用於建立5分鐘有效期間顯式緩衝的 Token 長度。

cache_creation_input_tokens integer

用於建立顯式緩衝的 Token 長度。

cache_type string

使用顯式緩衝時,參數值為ephemeral,否則該參數不存在。

錯誤碼

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