文件中心
 
全部產品
Search
  • 文件中心
  • Alibaba Cloud Model Studio
  • 操作指南(模型)
  • 文本產生
  • 深度思考

搜尋本產品

  • 搜尋本產品
  • 全部產品

    Alibaba Cloud Model Studio:深度思考

    文件中心

    Alibaba Cloud Model Studio:深度思考

    更新時間:Dec 05, 2025

    深度思考模型在產生回複前會先進行推理,以提升模型在邏輯推理與數值計算等複雜任務中的準確性。本文介紹如何調用 Qwen、DeepSeek 等支援深度思考的模型。

    QwQ Logo
    Qwen

    使用方式

    阿里雲百鍊提供多種深度思考模型 API,包含混合思考與僅思考兩種模式。

    • 混合思考模式:通過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

      # 匯入依賴...
      
      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

    • 商業版

      • 通義千問Max系列(混合思考模式,預設不開啟思考模式):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、qwen-turbo-latest、qwen-turbo-2025-04-28 及之後的快照版模型

    • 開源版

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

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

    QwQ (基於 Qwen2.5)

    僅思考模式:qwq-plus、qwq-plus-latest、qwq-plus-2025-03-05、qwq-32b

    DeepSeek(北京地區)

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

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

    Kimi(北京地區)

    僅思考模式:kimi-k2-thinking

    模型的名稱、上下文、價格、快照版本等資訊請參見模型列表;並發限流條件請參考限流。

    快速開始

    API 使用前提:已擷取與配置 API Key並完成配置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="sk-xxx"
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope-intl.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, // 從環境變數讀取
        baseURL: 'https://dashscope-intl.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

    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": "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

    Python

    範例程式碼

    import os
    from dashscope import Generation
    import dashscope
    dashscope.base_http_api_url = "https://dashscope-intl.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 {
            Constants.baseHttpApiUrl="https://dashscope-intl.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)
                    .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://dashscope.aliyuncs.com/api/v1/services/aigc/text-generation/generation
    # === 執行時請刪除該注釋 ===
    
    curl -X POST "https://dashscope-intl.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
    -H "Authorization: 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"}

    核心能力

    切換思考/非思考模式

    啟用思考模式通常可提升回複品質,但會增加響應延遲和成本。使用支援混合思考模式的模型時,可在不更換模型的前提下,根據問題複雜度動態切換思考或非思考模式:

    • 無需複雜推理(如日常聊天或簡單問答):可將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=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope-intl.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, 
        baseURL: 'https://dashscope-intl.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

    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": "user", 
                "content": "你是誰"
            }
        ],
        "stream": true,
        "stream_options": {
            "include_usage": true
        },
        "enable_thinking": true
    }'

    DashScope

    Python

    範例程式碼

    import os
    from dashscope import Generation
    import dashscope
    dashscope.base_http_api_url = "https://dashscope-intl.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",  # 設定結果格式為 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 {
                Generation gen = new Generation("http", "https://dashscope-intl.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

    curl -X POST "https://dashscope-intl.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": "你是誰?/no_think"
                }
            ]
        },
        "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、qwen-turbo-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=os.getenv("DASHSCOPE_API_KEY"),
        base_url="https://dashscope-intl.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, // 從環境變數讀取
        baseURL: 'https://dashscope-intl.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

    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": "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

    Python

    範例程式碼

    import os
    from dashscope import Generation
    import dashscope
    dashscope.base_http_api_url = "https://dashscope-intl.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 {
            Constants.baseHttpApiUrl="https://dashscope-intl.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

    curl -X POST "https://dashscope-intl.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"}

    其它功能

    • 多輪對話

    • 工具調用

    • 連網搜尋

    計費說明

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

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

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

    常見問題

    Q:怎麼關閉思考模式?

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

    • 若使用混合思考模式模型(如qwen-plus、deepseek-v3.2-exp),將enable_thinking設為false即可關閉;

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

    Q:哪些模型支援非流式輸出?

    深度思考模型在回複前需進行思考,導致等待回複時間變長,且非流式輸出有逾時風險,建議使用流式調用。如需非流式輸出,請使用以下支援的模型。

    Qwen3

    • 商業版

      • 通義千問Max系列:qwen3-max-preview

      • 通義千問Plus系列:qwen-plus

      • 通義千問Flash系列:qwen-flash、qwen-flash-2025-07-28

      • 通義千問Turbo系列:qwen-turbo

    • 開源版

      • qwen3-next-80b-a3b-thinking、qwen3-235b-a22b-thinking-2507、qwen3-30b-a3b-thinking-2507

    DeepSeek(北京地區)

    deepseek-v3.2-exp、deepseek-r1、deepseek-r1-0528、deepseek-r1蒸餾模型

    Kimi(北京地區)

    kimi-k2-thinking

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

    您可以訪問費用與成本中心進行儲值,確保您的賬戶沒有欠費即可調用模型。

    超出免費額度後,調用模型會自動計費,出賬周期為一小時,消費明細請前往賬單詳情進行查看。

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

    本文介紹模型僅支援文本輸入。Qwen3-VL、QVQ 模型支援對圖片進行深度思考。

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

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

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

    image

    API 參考

    深度思考模型的輸入與輸出參數請參見通義千問。

    錯誤碼

    如果執行報錯,請參見錯誤資訊進行解決。

    謝謝!我們已經收到了您的意見。