幫助中心
  • 操作指南(模型)
  • 使用者指南(應用)
  • API參考
  • API參考(應用)
  • 使用者指南(模型/香港)
  • API參考(模型/香港)
首頁 Alibaba Cloud Model Studio 操作指南(模型) 模型體驗 文本產生 深度思考

深度思考

更新時間:
Copy as MD
產品

深度思考模型在產生回複前先進行推理,從而在邏輯推理、數學計算等複雜任務中提升準確性。本文介紹如何通過API調用 Qwen、DeepSeek 等深度思考模型。

本文介紹如何通過 OpenAI 相容的 Chat Completion 介面或 DashScope 介面調用深度思考模型。 Responses API用法參見: 深度思考 。
QwQ Logo
Qwen

使用方式

百鍊深度思考模型分為兩種模式:

  • 混合思考模式:通過enable_thinking參數控制思考開關:

    • 設為true:模型先思考再回複;

    • 設為false:模型直接回複;

    OpenAI 相容

    # 匯入依賴與建立用戶端...
    completion = client.chat.completions.create(
        model="qwen-plus", # 選擇模型
        messages=[{"role": "user", "content": "你是誰"}],    
        # 由於 enable_thinking 非 OpenAI 標準參數,需要通過 extra_body 傳入
        extra_body={"enable_thinking":True},
        # 流式輸出方式調用
        stream=True,
        # 使流式返回的最後一個資料包包含Token消耗資訊
        stream_options={
            "include_usage": True
        }
    )

    DashScope

    Qwen3.5 系列的 DashScope API採用多模態介面,以下樣本會報錯 url error ,調用方式請參見 開啟/關閉思考模式 。
    # 匯入依賴...
    
    response = Generation.call(
        # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # 可按需更換為其它深度思考模型
        model="qwen-plus",
        messages=messages,
        result_format="message",
        enable_thinking=True,
        stream=True,
        incremental_output=True
    )
  • 僅思考模式:模型始終在回複前進行思考,無法關閉。除無需設定 enable_thinking 參數外,請求格式與混合思考模式一致。

思考內容通過reasoning_content欄位返回,回複內容通過content欄位返回。深度思考需要額外推理時間,加之多數模型僅支援流式輸出,本文樣本均採用流式調用。

支援的模型

Qwen3.7

千問3.7 Max系列(混合思考模式,預設開啟思考模式):qwen3.7-max、qwen3.7-max-2026-05-20、qwen3.7-max-2026-06-08

千問3.7 Max系列(僅支援思考模式):qwen3.7-max-preview、qwen3.7-max-2026-05-17

千問3.7 Plus系列(混合思考模式,預設開啟思考模式):qwen3.7-plus、qwen3.7-plus-2026-05-26

Qwen3.6

千問3.6 Max系列(混合思考模式,預設開啟思考模式):qwen3.6-max-preview

千問3.6 Plus系列(混合思考模式,預設開啟思考模式):qwen3.6-plus、qwen3.6-plus-2026-04-02

千問3.6 Flash系列(混合思考模式,預設開啟思考模式):qwen3.6-flash、qwen3.6-flash-2026-04-16

千問3.6 開源版:qwen3.6-35b-a3b

Qwen3.5

  • 商業版

    • 千問3.5 Plus系列(混合思考模式,預設開啟思考模式):qwen3.5-plus、qwen3.5-plus-2026-02-15

    • 千問3.5 Flash系列(混合思考模式,預設開啟思考模式):qwen3.5-flash、qwen3.5-flash-2026-02-23

  • 開源版

    • 混合思考模式,預設開啟思考模式:qwen3.5-397b-a17b、 qwen3.5-122b-a10b、qwen3.5-27b、qwen3.5-35b-a3b

Qwen3

  • 商業版

    • 千問Max系列:qwen3-max、qwen3-max-2026-01-23、qwen3-max-preview(混合思考模式,預設不開啟思考模式)

    • 千問Plus系列(混合思考模式,預設不開啟思考模式):qwen-plus、qwen-plus-latest、qwen-plus-2025-04-28 及之後的快照版模型

    • 千問Flash系列(混合思考模式,預設不開啟思考模式):qwen-flash、qwen-flash-2025-07-28 及之後的快照版模型

    • 千問Turbo系列(混合思考模式,預設不開啟思考模式):qwen-turbo 及之後的快照版模型

  • 開源版

    • 混合思考模式,預設開啟思考模式:qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b、qwen3-14b、qwen3-8b

    • 僅思考模式:qwen3-next-80b-a3b-thinking、qwen3-235b-a22b-thinking-2507、qwen3-30b-a3b-thinking-2507

QwQ (基於 Qwen2.5)

僅思考模式:qwq-plus

DeepSeek

  • 混合思考模式,預設開啟思考模式:deepseek-v4-pro、deepseek-v4-flash

  • 混合思考模式,預設不開啟思考模式:deepseek-v3.2、deepseek-v3.2-exp、deepseek-v3.1

  • 僅思考模式:deepseek-r1、deepseek-r1-0528、deepseek-r1蒸餾模型

GLM

混合思考模式,預設開啟思考模式:glm-5.1、glm-5、glm-4.7、glm-4.6

Kimi

  • 混合思考模式,預設關閉思考模式:kimi-k2.6、kimi-k2.5

  • 僅思考模式:kimi-k2.7-code、kimi-k2-thinking

MiniMax

僅思考模式:MiniMax-M2.5

快速開始

API 使用前提:已擷取API Key並完成配置API Key到環境變數。如果通過SDK調用,需要安裝 OpenAI 或 DashScope SDK(DashScope Java SDK需不低於 2.19.4 版本)。

以下代碼以流式調用 qwen-plus 開啟思考模式為例。

OpenAI相容

Python

範例程式碼

from openai import OpenAI
import os

# 初始化OpenAI用戶端
client = OpenAI(
    # 各地區的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"),
    # 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "你是誰"}]

completion = client.chat.completions.create(
    model="qwen-plus",  # 您可以按需更換為其它深度思考模型
    messages=messages,
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # 完整思考過程
answer_content = ""  # 完整回複
is_answering = False  # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\nUsage:")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # 只收集思考內容
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content

    # 收到content,開始進行回複
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

返回結果

====================思考過程====================

好的,使用者問“你是誰”,我需要給出一個準確且友好的回答。首先,我要確認自己的身份,即千問,由阿里巴巴集團旗下的通義實驗室研發。接下來,應該說明我的主要功能,比如回答問題、創作文字、邏輯推理等。同時,要保持語氣親切,避免過於技術化,讓使用者感覺輕鬆。還要注意不要使用複雜術語,確保回答簡潔明了。另外,可能需要加入一些互動元素,邀請使用者提問,促進進一步交流。最後,檢查是否有遺漏的重要訊息,比如我的中文名稱“千問”和英文名稱“Qwen”,以及所屬公司和實驗室。確保回答全面且符合使用者期望。
====================完整回複====================

你好!我是千問,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以回答問題、創作文字、進行邏輯推理、編程等,旨在為使用者提供高品質的資訊和服務。你可以叫我Qwen,或者直接叫我千問。有什麼我可以幫你的嗎?

Node.js

範例程式碼

import OpenAI from "openai";
import process from 'process';

// 初始化 openai 用戶端
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // 從環境變數讀取
    // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/compatible-mode/v1 
    // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = '';
let answerContent = '';
let isAnswering = false;

async function main() {
    try {
        const messages = [{ role: 'user', content: '你是誰' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            stream: true,
            enable_thinking: true
        });
        console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\nUsage:');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;
            
            // 只收集思考內容
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // 收到content,開始進行回複
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

返回結果

====================思考過程====================

好的,使用者問“你是誰”,我需要回答我的身份。首先,我應該明確說明我是千問,由阿里雲開發的超大規模語言模型。接下來,可以提到我的主要功能,比如回答問題、創作文字、邏輯推理等。還要強調我的多語言支援,包括中文和英文,這樣使用者知道我可以處理不同語言的請求。另外,可能需要解釋一下我的應用程式情境,比如學習、工作和生活中的協助。不過使用者的問題比較直接,可能不需要太詳細的資訊,保持簡潔明了。同時,要確保語氣友好,邀請使用者進一步提問。檢查有沒有遺漏的重要訊息,比如我的版本或最新更新,但可能使用者不需要那麼詳細。最後,確認回答準確無誤,沒有錯誤資訊。
====================完整回複====================

我是千問,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我能夠回答問題、創作文字、邏輯推理、編程等多種任務,支援中英文等多種語言。如果你有任何問題或需要幫,歡迎隨時告訴我!

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 以下是新加坡base_url,如果使用北京地區的模型,需要將base_url替換為:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# 如果使用維吉尼亞地區的模型,需要將base_url替換為:https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "user", 
            "content": "你是誰"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

返回結果

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

.....

data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":360,"total_tokens":370},"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: [DONE]

DashScope

Qwen3.5 系列的 DashScope API採用多模態介面,以下樣本會報錯 url error ,調用方式請參見 開啟/關閉思考模式 。

Python

範例程式碼

import os
from dashscope import Generation
import dashscope

# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

messages = [{"role": "user", "content": "你是誰?"}]

completion = Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-plus",
    messages=messages,
    result_format="message",
    enable_thinking=True,
    stream=True,
    incremental_output=True,
)

# 定義完整思考過程
reasoning_content = ""
# 定義完整回複
answer_content = ""
# 判斷是否結束思考過程並開始回複
is_answering = False

print("=" * 20 + "思考過程" + "=" * 20)

for chunk in completion:
    # 如果思考過程與回複皆為空白,則忽略
    if (
        chunk.output.choices[0].message.content == ""
        and chunk.output.choices[0].message.reasoning_content == ""
    ):
        pass
    else:
        # 如果當前為思考過程
        if (
            chunk.output.choices[0].message.reasoning_content != ""
            and chunk.output.choices[0].message.content == ""
        ):
            print(chunk.output.choices[0].message.reasoning_content, end="", flush=True)
            reasoning_content += chunk.output.choices[0].message.reasoning_content
        # 如果當前為回複
        elif chunk.output.choices[0].message.content != "":
            if not is_answering:
                print("\n" + "=" * 20 + "完整回複" + "=" * 20)
                is_answering = True
            print(chunk.output.choices[0].message.content, end="", flush=True)
            answer_content += chunk.output.choices[0].message.content

# 如果您需要列印完整思考過程與完整回複,請將以下代碼解除注釋後運行
# print("=" * 20 + "完整思考過程" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "完整回複" + "=" * 20 + "\n")
# print(f"{answer_content}")

返回結果

====================思考過程====================
好的,使用者問:“你是誰?”我需要回答這個問題。首先,我要明確自己的身份,即千問,由阿里雲開發的超大規模語言模型。接下來,要說明我的功能和用途,比如回答問題、創作文字、邏輯推理等。同時,要強調我的目標是成為使用者的得力助手,提供協助和支援。

在表達時,要保持口語化,避免使用專業術語或複雜句式。可以加入一些親切的語氣詞,比如“你好呀~”,讓對話更自然。另外,要確保資訊準確,不遺漏關鍵點,比如我的開發人員、主要功能和使用情境。

還要考慮使用者可能的後續問題,比如具體的應用例子或技術細節,所以在回答中可以適當埋下伏筆,引導使用者進一步提問。例如,提到“無論是日常生活的疑問還是專業領域的問題,我都能儘力提供協助”,這樣既全面又開放。

最後,檢查回答是否流暢,有沒有重複或冗餘的資訊,確保簡潔明了。同時,保持友好和專業的平衡,讓使用者感受到既親切又可靠。
====================完整回複====================
你好呀~我是千問,是阿里雲開發的一款超大規模語言模型。我能夠回答問題、創作文字、進行邏輯推理、編程等等,旨在為使用者提供協助和支援。無論是日常生活的疑問還是專業領域的問題,我都能儘力提供協助。有什麼我可以幫你的嗎?

Java

範例程式碼

// dashscope SDK的版本 >= 2.19.4
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 io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // 以下為新加坡地區base_url,若使用維吉尼亞地區模型,需要將base_url換成https://dashscope-us.aliyuncs.com/api/v1
        // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static StringBuilder reasoningContent = new StringBuilder();
    private static StringBuilder finalContent = new StringBuilder();
    private static boolean isFirstPrint = true;

    private static void handleGenerationResult(GenerationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================思考過程====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================完整回複====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.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("qwen-plus")
                .enableThinking(true)
                .incrementalOutput(true)
                .resultFormat("message")
                .messages(Arrays.asList(userMsg))
                .build();
    }
    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));
    }

    public static void main(String[] args) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是誰?").build();
            streamCallWithMessage(gen, userMsg);
//             列印最終結果
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================完整回複====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

返回結果

====================思考過程====================
好的,使用者問“你是誰?”,我需要根據之前的設定來回答。首先,我的角色是千問,阿里巴巴集團旗下的超大規模語言模型。要保持口語化,簡潔易懂。

使用者可能剛接觸我,或者想確認我的身份。應該先直接回答我是誰,然後簡要說明我的功能和用途,比如回答問題、創作文字、編程等。還要提到支援多語言,這樣使用者知道我可以處理不同語言的需求。

另外,根據指導方針,要保持擬人性,所以語氣要友好,可能用Emoji增加親切感。同時,可能需要引導使用者進一步提問或使用我的功能,比如問他們需要什麼協助。

需要注意不要使用複雜術語,避免冗長。檢查是否有遺漏的關鍵點,比如多語言支援和具體能力。確保回答符合所有要求,包括口語化和簡潔。
====================完整回複====================
你好!我是千問,阿里巴巴集團旗下的超大規模語言模型。我能夠回答問題、創作文字,比如寫故事、寫公文、寫郵件、寫劇本、邏輯推理、編程等,還能表達觀點,玩遊戲等。我熟練掌握多種語言,包括但不限於中文、英文、德語、法語、西班牙語等。有什麼需要我幫忙的嗎?

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區url,若使用北京地區的模型,需將url替換為:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# 若使用維吉尼亞地區的模型,需要將base_url替換為:https://dashscope-us.aliyuncs.com/api/v1/services/aigc/text-generation/generation
# === 執行時請刪除該注釋 ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "user",
                "content": "你是誰?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

返回結果

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"嗯","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"input_tokens":11,"output_tokens":3},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"input_tokens":11,"output_tokens":4},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"使用者","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":16,"input_tokens":11,"output_tokens":5},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"問","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":17,"input_tokens":11,"output_tokens":6},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"“","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":18,"input_tokens":11,"output_tokens":7},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
......

id:358
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"協助","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":373,"input_tokens":11,"output_tokens":362},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:359
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":",","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":374,"input_tokens":11,"output_tokens":363},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:360
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"歡迎","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":375,"input_tokens":11,"output_tokens":364},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:361
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"隨時","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":376,"input_tokens":11,"output_tokens":365},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:362
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"告訴我","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":377,"input_tokens":11,"output_tokens":366},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:363
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:364
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

核心能力

切換思考/非思考模式

啟用思考模式可提升回複品質,但會增加響應延遲和 Token 消耗。使用混合思考模式的模型時,可根據問題複雜度動態切換,無需更換模型:

  • 簡單任務(日常聊天、簡單問答):將enable_thinking設為false關閉思考;

  • 複雜任務(邏輯推理、代碼產生、數學解答):將enable_thinking設為true開啟思考。

OpenAI相容

重要

enable_thinking非 OpenAI 標準參數,若使用 OpenAI Python SDK請通過 extra_body傳入,Node.js SDK中作為頂層參數傳入。

Python

範例程式碼

from openai import OpenAI
import os

# 初始化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"),
    # 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "你是誰"}]
completion = client.chat.completions.create(
    model="qwen-plus",
    messages=messages,
    # 通過 extra_body 設定 enable_thinking 開啟思考過程
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # 完整思考過程
answer_content = ""  # 完整回複
is_answering = False  # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\n" + "=" * 20 + "Token 消耗" + "=" * 20 + "\n")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # 只收集思考內容
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content

    # 收到content,開始進行回複
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

返回結果

====================思考過程====================

嗯,使用者問“你是誰”,我需要先確定他們想知道什麼。可能他們第一次接觸我,或者想確認我的身份。我應該先介紹自己是千問,由通義實驗室研發。然後要說明我的功能,比如回答問題、創作文字、編程等,這樣使用者瞭解我能提供什麼協助。還要提到我支援多種語言,這樣國際使用者也會知道他們可以用不同語言交流。最後保持友好,邀請他們提問,這樣可以促進進一步互動。要注意簡潔明了,避免技術術語太多,讓使用者容易理解。可能使用者需要的是快速瞭解我的能力,所以重點放在功能和用途上。還要檢查有沒有遺漏的資訊,比如是否要提到阿里巴巴集團,或者更多技術細節。不過使用者可能只需要基本的資訊,不需要太深入。確保回答友好且專業,同時鼓勵使用者繼續提問。
====================完整回複====================

我是千問,由通義實驗室研發的超大規模語言模型。我可以協助你回答問題、創作文字、編程、表達觀點等,支援多語言交流。有什麼需要我幫忙的嗎?
====================Token 消耗====================

CompletionUsage(completion_tokens=221, prompt_tokens=10, total_tokens=231, completion_tokens_details=CompletionTokensDetails(accepted_prediction_tokens=None, audio_tokens=None, reasoning_tokens=172, rejected_prediction_tokens=None), prompt_tokens_details=PromptTokensDetails(audio_tokens=None, cached_tokens=0))

Node.js

範例程式碼

import OpenAI from "openai";
import process from 'process';

// 初始化OpenAI用戶端
const openai = new OpenAI({
    // 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY, 
    // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = ''; // 完整思考過程
let answerContent = ''; // 完整回複
let isAnswering = false; // 是否進入回複階段

async function main() {
    try {
        const messages = [{ role: 'user', content: '你是誰' }];
        
        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            // Node.js SDK 中,enable_thinking 等非標準參數作為頂層屬性傳遞,無需放在 extra_body 中
            enable_thinking: true,
            stream: true,
            stream_options: {
                include_usage: true
            },
        });

        console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\n' + '='.repeat(20) + 'Token 消耗' + '='.repeat(20) + '\n');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;
            
            // 只收集思考內容
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // 收到content,開始進行回複
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

返回結果

====================思考過程====================

嗯,使用者問“你是誰”,我需要先確定他們想知道什麼。可能他們第一次接觸我,或者想確認我的身份。我應該先介紹自己的名字和身份,比如千問,英文名Qwen。然後說明我是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。接下來要提到我的功能,比如回答問題、創作文字、編程、表達觀點等,這樣使用者能瞭解我的用途。還要提到我支援多語言,這樣國際使用者會覺得有用。最後邀請他們提問,保持友好和開放的態度。注意用簡潔易懂的語言,避免技術術語太多。可能使用者需要協助,或者只是好奇,所以回應要親切,鼓勵他們進一步互動。另外,可能需要考慮使用者是否有更深層的需求,比如測試我的能力或者尋找特定協助,但初次回答還是以基本資料和引導為主。保持口語化,不用複雜句子,讓資訊傳達更有效。
====================完整回複====================

你好!我是千問,英文名Qwen,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你回答問題、創作文字(比如寫故事、寫公文、寫郵件、寫劇本等)、進行邏輯推理、編程,甚至表達觀點和玩遊戲。我支援多種語言,包括但不限於中文、英文、德語、法語、西班牙語等。

如果你有任何問題或需要協助,隨時告訴我!
====================Token 消耗====================

{
  prompt_tokens: 10,
  completion_tokens: 288,
  total_tokens: 298,
  completion_tokens_details: { reasoning_tokens: 188 },
  prompt_tokens_details: { cached_tokens: 0 }
}

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/zh/model-studio/get-api-key
# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
# === 執行時請刪除該注釋 ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "user", 
            "content": "你是誰"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

DashScope

Qwen3.5 系列的 DashScope API採用多模態介面,以下樣本會報錯 url error ,調用方式請參見 開啟/關閉思考模式 。

Python

範例程式碼

import os
from dashscope import Generation
import dashscope

# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

# 初始化請求參數
messages = [{"role": "user", "content": "你是誰?"}]

completion = Generation.call(
    # 如果沒有配置環境變數,請用阿里雲百鍊API Key替換:api_key="sk-xxx"
    # 各地區的API Key不同。擷取API Key:請參考 https://www.alibabacloud.com/help/zh/model-studio/regions
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-plus",
    messages=messages,
    result_format="message",  # 設定結果格式為 message
    enable_thinking=True,     # 開啟思考過程
    stream=True,              # 開啟流式輸出
    incremental_output=True,  # 開啟增量輸出
)

reasoning_content = ""  # 完整思考過程
answer_content = ""     # 完整回複
is_answering = False    # 是否進入回複階段

print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")

for chunk in completion:
    message = chunk.output.choices[0].message
    
    # 只收集思考內容
    if message.reasoning_content:
        if not is_answering:
            print(message.reasoning_content, end="", flush=True)
        reasoning_content += message.reasoning_content

    # 收到 content,開始進行回複
    if message.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
            is_answering = True
        print(message.content, end="", flush=True)
        answer_content += message.content

print("\n" + "=" * 20 + "Token 消耗" + "=" * 20 + "\n")
print(chunk.usage)
# 迴圈結束後,reasoning_content 和 answer_content 變數中包含了完整的內容
# 您可以在這雷根據需要進行後續處理
# print(f"\n\n完整思考過程:\n{reasoning_content}")
# print(f"\n完整回複:\n{answer_content}")

返回結果

====================思考過程====================

嗯,使用者問“你是誰?”,我需要先確定他們想知道什麼。可能他們第一次接觸我,或者想確認我的身份。首先,我應該介紹自己的名字,千問,然後說明我是通義實驗室研發的超大規模語言模型。接下來,可能需要解釋我的功能,比如回答問題、創作文字、編程等,這樣使用者能瞭解我的用途。還要提到我支援多種語言,這樣國際使用者也能知道他們可以用不同語言交流。最後,保持友好,邀請他們提問,這樣能促進進一步的互動。要注意用簡潔易懂的語言,避免技術術語太多,讓使用者容易理解。可能使用者有更深層的需求,比如測試我的能力,或者尋找協助,所以提供具體的例子會更好,比如寫故事、寫公文、寫郵件等。還要確保回答結構清晰,分點說明功能,但可能不需要用項目符號,而是自然過渡。另外,要強調我是AI助手,沒有個人意識,所有回答都基於訓練資料,這樣避免誤解。可能需要檢查有沒有遺漏的重要訊息,比如多模態能力,或者最新的更新,但根據之前的回複,可能不需要太深入。總之,回答要全面但簡潔,友好且有協助,讓使用者感到被理解和支援。
====================完整回複====================

我是千問,阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我可以協助你:

1. **回答問題**:無論是學術問題、常識問題還是專業領域問題,我都可以嘗試為你解答。
2. **創作文字**:寫故事、寫公文、寫郵件、寫劇本等,我都可以幫你完成。
3. **邏輯推理**:我可以協助你進行邏輯推理和解決問題。
4. **編程**:我可以理解並產生多種程式設計語言的代碼。
5. **多語言支援**:我支援多種語言,包括但不限於中文、英文、德語、法語、西班牙語等。

如果你有任何問題或需要協助,隨時告訴我!
====================Token 消耗====================

{"input_tokens": 11, "output_tokens": 405, "total_tokens": 416, "output_tokens_details": {"reasoning_tokens": 256}, "prompt_tokens_details": {"cached_tokens": 0}}

Java

範例程式碼

// dashscope SDK的版本 >= 2.19.4
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.Constants;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static StringBuilder reasoningContent = new StringBuilder();
    private static StringBuilder finalContent = new StringBuilder();
    private static boolean isFirstPrint = true;

    private static void handleGenerationResult(GenerationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================思考過程====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================完整回複====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-plus")
                .enableThinking(true)
                .incrementalOutput(true)
                .resultFormat("message")
                .messages(Arrays.asList(userMsg))
                .build();
    }
    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));
    }

    public static void main(String[] args) {
        try {
            // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
            Generation gen = new Generation("http", "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是誰?").build();
            streamCallWithMessage(gen, userMsg);
//             列印最終結果
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================完整回複====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

返回結果

====================思考過程====================
嗯,使用者問“你是誰?”,我需要先確定他們想瞭解什麼。可能他們想知道我的身份,或者是在測試我的反應。首先,我應該明確回答我是千問,阿里巴巴集團旗下的超大規模語言模型。然後,可能需要簡要介紹我的功能,比如回答問題、創作文字、編程等,這樣使用者能瞭解我的用途。還要提到我支援多種語言,這樣國際使用者也會知道他們可以用不同語言交流。最後,保持友好,邀請他們提問,這樣他們會覺得親切,願意繼續互動。要注意回答不要太長,但資訊要全面。可能使用者還有後續問題,比如我的技術細節或者使用情境,但初次回答應該簡潔明了。確保沒有使用專業術語,讓所有使用者都能理解。檢查有沒有遺漏的重要訊息,比如多語言支援和具體功能例子。好的,這樣應該能覆蓋使用者的需求了。
====================完整回複====================
我是千問,阿里巴巴集團旗下的超大規模語言模型。我能夠回答問題、創作文字(如寫故事、寫公文、寫郵件、寫劇本等)、進行邏輯推理、編程、表達觀點、玩遊戲等,支援多語言交流,包括但不限於中文、英文、德語、法語、西班牙語等。如果你有任何問題或需要協助,歡迎隨時告訴我!

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/zh/model-studio/get-api-key
# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
# === 執行時請刪除該注釋 ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "user",
                "content": "你是誰?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

返回結果

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"嗯","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"input_tokens":11,"output_tokens":3},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"input_tokens":11,"output_tokens":4},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"使用者","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":16,"input_tokens":11,"output_tokens":5},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"問","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":17,"input_tokens":11,"output_tokens":6},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"“","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":18,"input_tokens":11,"output_tokens":7},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
......

id:358
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"協助","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":373,"input_tokens":11,"output_tokens":362},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:359
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":",","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":374,"input_tokens":11,"output_tokens":363},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:360
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"歡迎","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":375,"input_tokens":11,"output_tokens":364},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:361
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"隨時","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":376,"input_tokens":11,"output_tokens":365},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:362
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"告訴我","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":377,"input_tokens":11,"output_tokens":366},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:363
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

id:364
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}

此外,Qwen3 開源版混合思考模型以及 qwen-plus-2025-04-28 模型支援通過提示詞動態控制思考模式。enable_thinking為true時,在提示詞中加入/no_think可關閉思考;多輪對話中如需重新開啟,在最新提示詞中加入/think即可。模型始終遵循最新的/think或/no_think指令。

限制思考長度

深度思考模型有時會產生冗長的推理過程,增加等待時間並消耗更多 Token。通過thinking_budget參數可設定推理過程的最大 Token 數,超過限制後模型立即輸出回複。

thinking_budget 預設值為模型的最大思維鏈長度,請參見百鍊控制台的模型卡片。
重要

thinking_budget參數支援 Qwen3(思考模式)與Kimi模型。

OpenAI相容

Python

範例程式碼

from openai import OpenAI
import os

# 初始化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"),
    # 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "你是誰"}]

completion = client.chat.completions.create(
    model="qwen-plus",
    messages=messages,
    # enable_thinking 參數開啟思考過程,thinking_budget 參數設定最大推理過程 Token 數
    extra_body={
        "enable_thinking": True,
        "thinking_budget": 50
        },
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # 完整思考過程
answer_content = ""  # 完整回複
is_answering = False  # 是否進入回複階段
print("\n" + "=" * 20 + "思考過程" + "=" * 20 + "\n")

for chunk in completion:
    if not chunk.choices:
        print("\nUsage:")
        print(chunk.usage)
        continue

    delta = chunk.choices[0].delta

    # 只收集思考內容
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content

    # 收到content,開始進行回複
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "完整回複" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

返回結果

====================思考過程====================

好的,使用者問“你是誰”,我需要給出一個清晰且友好的回答。首先,應該明確自己的身份,即千問,由阿里巴巴集團旗下的通義實驗室研發。接下來,要說明自己的主要功能,比如回答
====================完整回複====================

我是千問,是阿里巴巴集團旗下的通義實驗室研發的超大規模語言模型。我能夠回答問題、創作文字、邏輯推理、編程等,旨在為使用者提供協助和便利。有什麼我可以幫您的嗎?

Node.js

範例程式碼

import OpenAI from "openai";
import process from 'process';

// 初始化 openai 用戶端
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // 從環境變數讀取
    // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = '';
let answerContent = '';
let isAnswering = false;

async function main() {
    try {
        const messages = [{ role: 'user', content: '你是誰' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            stream: true,
            // enable_thinking 參數開啟思考過程,thinking_budget 參數設定最大推理過程 Token 數
            enable_thinking: true,
            thinking_budget: 50
        });
        console.log('\n' + '='.repeat(20) + '思考過程' + '='.repeat(20) + '\n');

        for await (const chunk of stream) {
            if (!chunk.choices?.length) {
                console.log('\nUsage:');
                console.log(chunk.usage);
                continue;
            }

            const delta = chunk.choices[0].delta;
            
            // 只收集思考內容
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // 收到content,開始進行回複
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + '完整回複' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

返回結果

====================思考過程====================

好的,使用者問“你是誰”,我需要給出一個清晰準確的回答。首先,我應該介紹自己的身份,即千問,由阿里巴巴集團旗下的通義實驗室研發。接下來,要說明我的主要功能,比如回答問題
====================完整回複====================

我是千問,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我能夠回答問題、創作文字、邏輯推理、編程等多種任務。如果你有任何問題或需要協助,歡迎隨時告訴我!

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 以下是新加坡base_url,如果使用北京地區的模型,需要將base_url替換為:https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# 如果使用維吉尼亞地區的模型,需要將base_url替換為:https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# === 執行時請刪除該注釋 ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen-plus",
    "messages": [
        {
            "role": "user", 
            "content": "你是誰"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true,
    "thinking_budget": 50
}'

返回結果

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

.....

data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":360,"total_tokens":370},"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: [DONE]

DashScope

Qwen3.5 系列的 DashScope API採用多模態介面,以下樣本會報錯 url error ,調用方式請參見 開啟/關閉思考模式 。

Python

範例程式碼

import os
from dashscope import Generation
import dashscope

# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

messages = [{"role": "user", "content": "你是誰?"}]

completion = Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen-plus",
    messages=messages,
    result_format="message",
    enable_thinking=True,
    # 設定最大推理過程 Token 數
    thinking_budget=50,
    stream=True,
    incremental_output=True,
)

# 定義完整思考過程
reasoning_content = ""
# 定義完整回複
answer_content = ""
# 判斷是否結束思考過程並開始回複
is_answering = False

print("=" * 20 + "思考過程" + "=" * 20)

for chunk in completion:
    # 如果思考過程與回複皆為空白,則忽略
    if (
        chunk.output.choices[0].message.content == ""
        and chunk.output.choices[0].message.reasoning_content == ""
    ):
        pass
    else:
        # 如果當前為思考過程
        if (
            chunk.output.choices[0].message.reasoning_content != ""
            and chunk.output.choices[0].message.content == ""
        ):
            print(chunk.output.choices[0].message.reasoning_content, end="", flush=True)
            reasoning_content += chunk.output.choices[0].message.reasoning_content
        # 如果當前為回複
        elif chunk.output.choices[0].message.content != "":
            if not is_answering:
                print("\n" + "=" * 20 + "完整回複" + "=" * 20)
                is_answering = True
            print(chunk.output.choices[0].message.content, end="", flush=True)
            answer_content += chunk.output.choices[0].message.content

# 如果您需要列印完整思考過程與完整回複,請將以下代碼解除注釋後運行
# print("=" * 20 + "完整思考過程" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "完整回複" + "=" * 20 + "\n")
# print(f"{answer_content}")

返回結果

====================思考過程====================
好的,使用者問“你是誰?”,我需要給出一個清晰且友好的回答。首先,我要介紹自己的身份,也就是千問,由阿里巴巴集團旗下的通義實驗室研發。接下來,應該說明我的主要功能,比如
====================完整回複====================
我是千問,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我能夠回答問題、創作文字、邏輯推理、編程等,旨在為使用者提供全面、準確和有用的資訊與協助。有什麼我可以幫您的嗎?

Java

範例程式碼

// dashscope SDK的版本 >= 2.19.4
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 io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
        Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
    }
    private static final Logger logger = LoggerFactory.getLogger(Main.class);
    private static StringBuilder reasoningContent = new StringBuilder();
    private static StringBuilder finalContent = new StringBuilder();
    private static boolean isFirstPrint = true;

    private static void handleGenerationResult(GenerationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        String content = message.getOutput().getChoices().get(0).getMessage().getContent();

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================思考過程====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================完整回複====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static GenerationParam buildGenerationParam(Message userMsg) {
        return GenerationParam.builder()
                // 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:.apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen-plus")
                .enableThinking(true)
                .thinkingBudget(50)
                .incrementalOutput(true)
                .resultFormat("message")
                .messages(Arrays.asList(userMsg))
                .build();
    }
    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));
    }

    public static void main(String[] args) {
        try {
            Generation gen = new Generation();
            Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是誰?").build();
            streamCallWithMessage(gen, userMsg);
//             列印最終結果
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================完整回複====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

返回結果

====================思考過程====================
好的,使用者問“你是誰?”,我需要給出一個清晰且友好的回答。首先,我要介紹自己的身份,也就是千問,由阿里巴巴集團旗下的通義實驗室研發。接下來,應該說明我的主要功能,比如
====================完整回複====================
我是千問,是阿里巴巴集團旗下的通義實驗室自主研發的超大規模語言模型。我能夠回答問題、創作文字、邏輯推理、編程等,旨在為使用者提供全面、準確和有用的資訊與協助。有什麼我可以幫您的嗎?

HTTP

範例程式碼

curl

# ======= 重要提示 =======
# 各地區的API Key不同。擷取API Key:https://www.alibabacloud.com/help/zh/model-studio/get-api-key
# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
# === 執行時請刪除該注釋 ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen-plus",
    "input":{
        "messages":[      
            {
                "role": "user",
                "content": "你是誰?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "thinking_budget": 50,
        "incremental_output": true,
        "result_format": "message"
    }
}'

返回結果

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"好的","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"output_tokens":3,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"output_tokens":4,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":2}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}

......

id:133
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":149,"output_tokens":138,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":50}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}

id:134
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":149,"output_tokens":138,"input_tokens":11,"output_tokens_details":{"reasoning_tokens":50}},"request_id":"2ce91085-3602-9c32-9c8b-fe3d583a2c38"}

傳遞思考過程

多輪對話中,模型預設不會讀取歷史訊息裡的messages數組中的reasoning_content。將preserve_thinking設為true後,assistant 訊息中的reasoning_content將被拼接到下一輪輸入,讓模型參考之前的推理過程。

重要

preserve_thinking參數僅支援 qwen3.7-max、qwen3.7-max-2026-05-20、qwen3.7-max-2026-06-08、qwen3.7-max-preview、qwen3.7-max-2026-05-17、qwen3.7-plus、qwen3.7-plus-2026-05-26、qwen3.6-max-preview、qwen3.6-plus、qwen3.6-plus-2026-04-02、kimi-k2.7-code(阿里雲百鍊部署)、kimi-k2.6(阿里雲百鍊部署)、kimi/kimi-k2.7-code-highspeed(月之暗面部署)、kimi/kimi-k2.7-code(月之暗面部署)、kimi/kimi-k2.6(月之暗面部署)。

若歷史訊息中不包含 reasoning_content ,開啟此參數不會報錯。
開啟後,歷史對話中的 reasoning_content 會計入輸入 Token 數量和計費。

OpenAI相容

說明

preserve_thinking非 OpenAI 標準參數,使用 Python SDK需通過extra_body傳入。

Python

範例程式碼

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# 第一輪對話
messages = [
    {"role": "user", "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"}
]

first_reasoning = ""
first_content = ""
is_answering = False

completion = client.chat.completions.create(
    model="qwen3.7-plus",
    messages=messages,
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={"include_usage": True},
)

print("=" * 20 + "第一輪思考過程" + "=" * 20)

for chunk in completion:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        first_reasoning += delta.reasoning_content
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "第一輪迴複" + "=" * 20)
            is_answering = True
        print(delta.content, end="", flush=True)
        first_content += delta.content

# 第二輪對話:傳遞思考過程,追問模型為什麼排除了Kafka
messages = [
    {"role": "user", "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"},
    {
        "role": "assistant",
        "content": first_content,
        "reasoning_content": first_reasoning,
    },
    {"role": "user", "content": "你在對比時為什麼排除了Kafka?"},
]

reasoning_content = ""
answer_content = ""
is_answering = False

# preserve_thinking 通過 extra_body 傳入
completion = client.chat.completions.create(
    model="qwen3.7-plus",
    messages=messages,
    extra_body={
        "enable_thinking": True,
        "preserve_thinking": True,
    },
    stream=True,
    stream_options={"include_usage": True},
)

print("\n" + "=" * 20 + "第二輪思考過程" + "=" * 20)

for chunk in completion:
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta
    if hasattr(delta, "reasoning_content") and delta.reasoning_content is not None:
        if not is_answering:
            print(delta.reasoning_content, end="", flush=True)
        reasoning_content += delta.reasoning_content
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "第二輪迴複" + "=" * 20)
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

返回結果

====================第一輪思考過程====================
使用者需要為日均千萬訊息的電商系統選擇訊息佇列。讓我從輸送量、可靠性、延遲訊息、事務支援等維度對比主流方案...

RocketMQ:阿里電商情境驗證,原生支援事務訊息和延遲訊息,分區級嚴格有序...
Kafka:極高輸送量,但無原生事務訊息和延遲訊息支援,需自研補償機制...
RabbitMQ:延遲低,但叢集擴充能力有限,峰值萬級TPS...
====================第一輪迴複====================
綜合電商情境的核心需求(事務訊息、延遲訊息、順序性、峰值應對),推薦 Apache RocketMQ。如果團隊已有 Kafka 生態或需強即時分析能力,Kafka 也是可行方案。
====================第二輪思考過程====================
使用者在追問為什麼排除了Kafka。回顧我的歷史思考過程,我並沒有排除Kafka,而是給了它4星評分。讓我參考之前的詳細對比分析來解釋...

在上一輪思考中,我對比了RocketMQ和Kafka在事務訊息、延遲訊息、順序性方面的差異。Kafka的劣勢主要在於需要額外架構設計來補齊電商特有語義...
====================第二輪迴複====================
我並沒有排除Kafka。Kafka在輸送量和生態方面表現優秀,之所以RocketMQ評分略高,是因為電商核心鏈路的"開箱即用"特性匹配度:RocketMQ原生支援事務訊息和延遲訊息,而Kafka需要通過Outbox Pattern等架構模式自行實現。如果團隊已有Kafka生態,它完全能勝任千萬級訊息情境。

Node.js

範例程式碼

import OpenAI from "openai";
import process from 'process';

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

async function main() {
    // 第一輪對話
    let firstReasoning = '';
    let firstContent = '';
    let isAnswering = false;

    const stream1 = await openai.chat.completions.create({
        model: 'qwen3.7-plus',
        messages: [{ role: 'user', content: '我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦' }],
        stream: true,
        enable_thinking: true
    });

    console.log('='.repeat(20) + '第一輪思考過程' + '='.repeat(20));

    for await (const chunk of stream1) {
        if (!chunk.choices?.length) continue;
        const delta = chunk.choices[0].delta;
        if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
            firstReasoning += delta.reasoning_content;
            if (!isAnswering) process.stdout.write(delta.reasoning_content);
        }
        if (delta.content !== undefined && delta.content) {
            if (!isAnswering) {
                console.log('\n' + '='.repeat(20) + '第一輪迴複' + '='.repeat(20));
                isAnswering = true;
            }
            process.stdout.write(delta.content);
            firstContent += delta.content;
        }
    }

    // 第二輪對話:傳遞思考過程
    let reasoningContent = '';
    let answerContent = '';
    isAnswering = false;

    const stream2 = await openai.chat.completions.create({
        model: 'qwen3.7-plus',
        messages: [
            { role: 'user', content: '我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦' },
            {
                role: 'assistant',
                content: firstContent,
                reasoning_content: firstReasoning
            },
            { role: 'user', content: '你在對比時為什麼排除了Kafka?' }
        ],
        stream: true,
        enable_thinking: true,
        // preserve_thinking 作為頂層參數傳入
        preserve_thinking: true
    });

    console.log('\n' + '='.repeat(20) + '第二輪思考過程' + '='.repeat(20));

    for await (const chunk of stream2) {
        if (!chunk.choices?.length) continue;
        const delta = chunk.choices[0].delta;
        if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
            if (!isAnswering) process.stdout.write(delta.reasoning_content);
            reasoningContent += delta.reasoning_content;
        }
        if (delta.content !== undefined && delta.content) {
            if (!isAnswering) {
                console.log('\n' + '='.repeat(20) + '第二輪迴複' + '='.repeat(20));
                isAnswering = true;
            }
            process.stdout.write(delta.content);
            answerContent += delta.content;
        }
    }
}

main();

返回結果

====================第一輪思考過程====================
使用者需要為日均千萬訊息的電商系統選擇訊息佇列。讓我從輸送量、可靠性、延遲訊息、事務支援等維度對比主流方案...
====================第一輪迴複====================
綜合電商情境的核心需求,推薦 Apache RocketMQ。如果團隊已有 Kafka 生態,Kafka 也是可行方案。
====================第二輪思考過程====================
使用者追問為什麼排除了Kafka。參考我之前的思考過程,我並沒有排除Kafka...
====================第二輪迴複====================
我並沒有排除Kafka。Kafka在輸送量和生態方面表現優秀,之所以RocketMQ評分略高,是因為電商核心鏈路的"開箱即用"特性匹配度。

HTTP

範例程式碼

curl

# 各地區base_url不同,請根據實際地區修改
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
    "model": "qwen3.7-plus",
    "messages": [
        {
            "role": "user",
            "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"
        },
        {
            "role": "assistant",
            "content": "綜合電商情境的核心需求,推薦 Apache RocketMQ。",
            "reasoning_content": "使用者需要為日均千萬訊息的電商系統選擇訊息佇列。RocketMQ原生支援事務訊息和延遲訊息,更適合電商情境。Kafka輸送量極高但需自研補償機制。"
        },
        {
            "role": "user",
            "content": "你在對比時為什麼排除了Kafka?"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true,
    "preserve_thinking": true
}'

返回結果

data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1743523200,"system_fingerprint":null,"model":"qwen3.7-plus","id":"chatcmpl-example-001"}

.....

data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1743523200,"system_fingerprint":null,"model":"qwen3.7-plus","id":"chatcmpl-example-001"}

data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":3463,"completion_tokens":2387,"total_tokens":5850},"created":1743523200,"system_fingerprint":null,"model":"qwen3.7-plus","id":"chatcmpl-example-001"}

data: [DONE]

DashScope

說明

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

Python

範例程式碼

import os
from dashscope import Generation
import dashscope

# 以下為新加坡地區配置,調用時請將WorkspaceId替換為真實的業務空間ID,各地區的配置不同。
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

# 第一輪對話
messages = [
    {"role": "user", "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"}
]

first_reasoning = ""
first_content = ""
is_answering = False

completion = Generation.call(
    # 若沒有配置環境變數,請用阿里雲百鍊API Key將下行替換為:api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.7-plus",
    messages=messages,
    result_format="message",
    enable_thinking=True,
    stream=True,
    incremental_output=True,
)

print("=" * 20 + "第一輪思考過程" + "=" * 20)

for chunk in completion:
    if (
        chunk.output.choices[0].message.content == ""
        and chunk.output.choices[0].message.reasoning_content == ""
    ):
        pass
    else:
        if (
            chunk.output.choices[0].message.reasoning_content != ""
            and chunk.output.choices[0].message.content == ""
        ):
            print(chunk.output.choices[0].message.reasoning_content, end="", flush=True)
            first_reasoning += chunk.output.choices[0].message.reasoning_content
        elif chunk.output.choices[0].message.content != "":
            if not is_answering:
                print("\n" + "=" * 20 + "第一輪迴複" + "=" * 20)
                is_answering = True
            print(chunk.output.choices[0].message.content, end="", flush=True)
            first_content += chunk.output.choices[0].message.content

# 第二輪對話:傳遞思考過程
messages = [
    {"role": "user", "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"},
    {
        "role": "assistant",
        "content": first_content,
        "reasoning_content": first_reasoning,
    },
    {"role": "user", "content": "你在對比時為什麼排除了Kafka?"},
]

reasoning_content = ""
answer_content = ""
is_answering = False

completion = Generation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.7-plus",
    messages=messages,
    result_format="message",
    enable_thinking=True,
    # 傳遞思考過程
    preserve_thinking=True,
    stream=True,
    incremental_output=True,
)

print("\n" + "=" * 20 + "第二輪思考過程" + "=" * 20)

for chunk in completion:
    if (
        chunk.output.choices[0].message.content == ""
        and chunk.output.choices[0].message.reasoning_content == ""
    ):
        pass
    else:
        if (
            chunk.output.choices[0].message.reasoning_content != ""
            and chunk.output.choices[0].message.content == ""
        ):
            print(chunk.output.choices[0].message.reasoning_content, end="", flush=True)
            reasoning_content += chunk.output.choices[0].message.reasoning_content
        elif chunk.output.choices[0].message.content != "":
            if not is_answering:
                print("\n" + "=" * 20 + "第二輪迴複" + "=" * 20)
                is_answering = True
            print(chunk.output.choices[0].message.content, end="", flush=True)
            answer_content += chunk.output.choices[0].message.content

返回結果

====================第一輪思考過程====================
使用者需要為日均千萬訊息的電商系統選擇訊息佇列。讓我從輸送量、可靠性、延遲訊息、事務支援等維度對比主流方案...
====================第一輪迴複====================
綜合電商情境的核心需求,推薦 Apache RocketMQ。如果團隊已有 Kafka 生態,Kafka 也是可行方案。
====================第二輪思考過程====================
使用者追問為什麼排除了Kafka。參考我之前的思考過程,我並沒有排除Kafka...
====================第二輪迴複====================
我並沒有排除Kafka。Kafka在輸送量和生態方面表現優秀,之所以RocketMQ評分略高,是因為電商核心鏈路的"開箱即用"特性匹配度。

HTTP

範例程式碼

curl

# 各地區base_url不同,請根據實際地區修改
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.7-plus",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": "我需要為一個日均千萬訊息的電商系統選擇訊息佇列,請推薦"
            },
            {
                "role": "assistant",
                "content": "綜合電商情境的核心需求,推薦 Apache RocketMQ。",
                "reasoning_content": "使用者需要為日均千萬訊息的電商系統選擇訊息佇列。RocketMQ原生支援事務訊息和延遲訊息,更適合電商情境。Kafka輸送量極高但需自研補償機制。"
            },
            {
                "role": "user",
                "content": "你在對比時為什麼排除了Kafka?"
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "preserve_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

返回結果

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"使用者","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":3466,"output_tokens":3,"input_tokens":3463,"output_tokens_details":{"reasoning_tokens":1}},"request_id":"example-request-001"}

id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"追問","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":3467,"output_tokens":4,"input_tokens":3463,"output_tokens_details":{"reasoning_tokens":2}},"request_id":"example-request-001"}

......

id:200
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":5850,"output_tokens":2387,"input_tokens":3463,"output_tokens_details":{"reasoning_tokens":1347}},"request_id":"example-request-001"}

其他功能

  • 多輪對話

  • 工具調用

  • 連網搜尋

計費說明

  • 思考內容按輸出 Token 計費。

  • 部分混合思考模型在思考與非思考模式下價格不同。

    模型在思考模式下若未輸出思考過程,按非思考模式價格計費。

常見問題

Q:怎麼關閉思考模式?

是否能關閉思考模式取決於所用模型:

  • 混合思考模式模型(如 qwen3.6-plus、deepseek-v4-pro):將 enable_thinking 設為 false 即可關閉;

  • 僅思考模式模型(如 qwen3-235b-a22b-thinking-2507、deepseek-r1):無法關閉。

Q:免費額度用完後如何購買 Token?

前往費用與成本中心儲值,保持賬戶餘額充足即可正常調用模型。

超出免費額度後自動計費,出賬周期為分鐘級,消費明細請前往 ** 賬單詳情** 進行查看。

Q:可以上傳圖片或文檔進行提問嗎?

本文涉及的模型僅支援文本輸入。Qwen3-VL、QVQ 模型支援圖片深度思考。

Q:如何查看Token消耗量及調用次數?

模型調用完一小時後,在模型監控(新加坡或北京)版面設定查詢條件(例如,選擇時間範圍、業務空間等),再在模型列表地區找到目標模型並單擊操作列的监控,即可查看該模型的調用統計結果。具體請參見模型監控文檔。

資料按小時更新,高峰期可能有小時級延遲,請您耐心等待。

image

API 參考

深度思考模型的輸入輸出參數,請參見文本產生。

錯誤碼

執行報錯時,請參見錯誤碼排查解決。

上一篇:流式輸出下一篇:首碼續寫
该文章对您有帮助吗?