Tous les produits
Search
Centre de documentation

Alibaba Cloud Model Studio:Raisonnement approfondi

Dernière mise à jour :Oct 19, 2026

Les modèles de raisonnement approfondi analysent la demande avant d'y répondre, ce qui améliore leur précision sur des tâches complexes telles que le raisonnement logique et les mathématiques.

Ces exemples utilisent l'API Chat Completion compatible OpenAI ainsi que l'API DashScope. Pour l'API Responses, consultez Raisonnement approfondi .

Utilisation

Model Studio prend en charge le raisonnement approfondi selon deux modes :

  • Mode de raisonnement hybride : utilisez le paramètre enable_thinking pour activer ou désactiver le raisonnement à chaque requête :

    • Définissez-le sur true : le modèle effectue un raisonnement avant de répondre.
    • Définissez-le sur false : le modèle répond directement sans étape de raisonnement.

    Compatible OpenAI

    # Import dependencies and create a client...
    completion = client.chat.completions.create(
        model="qwen3.8-max", # Select a model
        messages=[{"role": "user", "content": "Who are you"}],
        # Since enable_thinking is not a standard OpenAI parameter, pass it in extra_body.
        extra_body={"enable_thinking":True},
        # Enable streaming output.
        stream=True,
        # Configure the stream to include token consumption information in the last data packet.
        stream_options={
            "include_usage": True
        }
    )
    

    DashScope

    L'API DashScope pour la série Qwen3.5 utilise une interface multimodale. L'exemple suivant renvoie une url error . Pour une utilisation correcte, consultez Activer ou désactiver le mode de raisonnement .

    # Import dependencies...
    
    response = MultiModalConversation.call(
        # If you have not set the environment variable, replace the next line with your Model Studio API key, for example: api_key = "sk-xxx",
        api_key=os.getenv("DASHSCOPE_API_KEY"),
        # You can use other deep thinking models as needed.
        model="qwen3.8-max",
        messages=messages,
        enable_thinking=True,
        stream=True,
        incremental_output=True
    )
    
  • Mode raisonnement uniquement : le modèle effectue systématiquement un raisonnement avant de répondre ; ce comportement ne peut pas être désactivé. Le format de requête est identique à celui du mode hybride, mais aucun paramètre enable_thinking n'est nécessaire.

L'API retourne le raisonnement dans le champ reasoning_content et la réponse dans le champ content. Le raisonnement ajoutant de la latence, tous les exemples utilisent par défaut le streaming (recommandé pour observer le processus en temps réel). Les modèles commerciaux de raisonnement prennent également en charge la sortie non-streaming (synchrone) ; consultez la FAQ ci-dessous pour les détails d'utilisation et les précautions à prendre. Certains modèles (comme les versions open source qwen3.5-122b-a10b et qwen3.5-27b) ne supportent que le streaming ; un appel non-streaming générera alors une erreur.

Modèles pris en charge

Qwen3.8

Série Qwen3.8 Max (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.8-max

Qwen3.7

Série Qwen3.7 Max (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.7-max, qwen3.7-max-us, qwen3.7-max-2026-05-20, qwen3.7-max-2026-06-08

Série Qwen3.7 Max (mode raisonnement uniquement) : qwen3.7-max-preview, qwen3.7-max-2026-05-17

Série Qwen3.7 Plus (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.7-plus, qwen3.7-plus-us, qwen3.7-plus-2026-05-26

Série Qwen3.7 Flash (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.7-flash, qwen3.7-flash-2026-07-15

Qwen3.6

Série Qwen3.6 Plus (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.6-plus, qwen3.6-plus-2026-04-02

Série Qwen3.6 Flash (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.6-flash, qwen3.6-flash-2026-04-16

Qwen3.6 open source : qwen3.6-35b-a3b

Qwen3.5

  • Commercial
    • Série Qwen3.5 Plus (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.5-plus, qwen3.5-plus-2026-02-15
    • Série Qwen3.5 Flash (mode de raisonnement hybride, raisonnement activé par défaut) : qwen3.5-flash, qwen3.5-flash-2026-02-23

Qwen3

  • Commercial
    • Série Qwen Plus (mode de raisonnement hybride, raisonnement désactivé par défaut) : qwen-plus, qwen-plus-latest, qwen-plus-2025-04-28 et versions snapshot ultérieures
    • Série Qwen Flash (mode de raisonnement hybride, raisonnement désactivé par défaut) : qwen-flash, qwen-flash-2025-07-28 et versions snapshot ultérieures

DeepSeek

  • Déployé sur Alibaba Cloud Model Studio

    • deepseek-v4.1-flash-1017 prend en charge le raisonnement approfondi.
    • Mode de raisonnement hybride, raisonnement désactivé par défaut : deepseek-v4-pro
    • Mode raisonnement uniquement : modèles distillés deepseek-r1
  • Déployé sur SiliconFlow

    • Mode de raisonnement hybride, raisonnement désactivé par défaut : siliconflow/deepseek-v3.2, siliconflow/deepseek-v3.1-terminus
    • Mode raisonnement uniquement : siliconflow/deepseek-r1-0528
  • Déployé sur Kuaishou Vanchin

    • Mode de raisonnement hybride, raisonnement désactivé par défaut : vanchin/deepseek-v3.2-think, vanchin/deepseek-v3.1-terminus
    • Mode raisonnement uniquement : vanchin/deepseek-r1

GLM

Mode de raisonnement hybride, raisonnement activé par défaut : glm-5.2, glm-5.2-us, glm-5.2-fast-preview, glm-5.1, glm-5

Kimi

  • Déployé sur Alibaba Cloud Model Studio

    • Mode de raisonnement hybride, raisonnement désactivé par défaut : kimi-k2.6, kimi-k2.5
    • Mode raisonnement uniquement : kimi-k2.7-code
  • Déployé sur Moonshot AI

    • Mode de raisonnement hybride, raisonnement activé par défaut : kimi/kimi-k2.6, kimi/kimi-k2.5
    • Mode raisonnement uniquement : kimi/kimi-k2.7-code-highspeed, kimi/kimi-k2.7-code

MiniMax

  • Déployé sur Alibaba Cloud Model Studio

    • Mode raisonnement uniquement : MiniMax-M2.5

Les noms des modèles, les fenêtres de contexte, les tarifs et les versions snapshot sont disponibles dans la Liste des modèles. Les limites de taux sont décrites dans la rubrique Limitation du débit.

Prise en main

Obtenez une clé API et définissez-la comme variable d'environnement. Si vous utilisez un SDK, installez le SDK OpenAI ou DashScope (le SDK Java DashScope version 2.19.4 ou ultérieure est requis).

L'exemple suivant appelle qwen3.8-max en mode raisonnement avec une sortie en streaming.

Compatible OpenAI

Python

Exemple de code

from openai import OpenAI
import os

# Initialize the OpenAI client.
client = OpenAI(
    # API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If an environment variable is not configured, provide your Model Studio API key directly: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Configurations vary by region. Modify the base_url based on your region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you"}]

completion = client.chat.completions.create(
    model="qwen3.8-max",  # You can replace this with other deep-thinking models as needed.
    messages=messages,
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Full thinking process
answer_content = ""  # Full response
is_answering = False  # Tracks if the response phase has started
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

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

    delta = chunk.choices[0].delta

    # Collect only the reasoning content.
    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

    # When content is received, start responding.
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Réponse

====================Thinking process====================

The user's query "Who are you?" requires an accurate and friendly response. The answer should first establish my identity as Qwen, developed by Tongyi Lab at Alibaba Cloud. It will then outline key capabilities such as question answering, text generation, and logical reasoning. The language must be simple and the tone approachable. To encourage interaction, I will invite the user to ask more questions. Finally, I'll check that all key details are present, including my name (Qwen) and developer, to provide a comprehensive answer.
====================Full response====================

Hello! I am Qwen, a large language model developed by Tongyi Lab at Alibaba Group. I can answer questions, generate text, perform logical reasoning, write code, and more, to provide you with high-quality information and services. You can call me Qwen. How can I help you?

Node.js

Exemple de code

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

// Initialize the OpenAI client.
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // Read from an environment variable.
    // The following is the base URL for the Singapore region. If you use models in the US (Virginia) region, change the base URL to https://dashscope-us.aliyuncs.com/compatible-mode/v1. The base URL varies by region. Update it for your deployment's region.
    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: 'Who are you' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            stream: true,
            enable_thinking: true
        });
        console.log('\n' + '='.repeat(20) + 'Thinking process' + '='.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;

            // Collect only the reasoning content.
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // When content is received, start responding.
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + 'Full response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Réponse

====================Thinking process====================

The user's direct query "Who are you?" requires a concise and clear response. The answer will state my identity as Qwen, a large language model from Alibaba Cloud. It will mention key functions like question answering, text generation, and logical reasoning, and highlight multilingual support (Chinese, English). To remain concise, use cases will be mentioned briefly, if at all. The tone will be friendly, and the response will end with an invitation for further questions. Finally, I'll check to ensure accuracy without including unnecessary details like version numbers.
====================Full response====================

I am Qwen, a large language model developed by Tongyi Lab at Alibaba Group. I can perform a variety of tasks, including answering questions, generating text, logical reasoning, and coding, and I support multiple languages, including Chinese and English. If you have any questions or need help, feel free to ask me at any time!

HTTP

Exemple de code

curl

# ======= Important =======
# The following URL is for the Singapore region. For the China (Beijing) region, replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# For the US (Virginia) region, replace it with: https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# === Remove this comment before execution ===
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.8-max",
    "messages": [
        {
            "role": "user",
            "content": "Who are you"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

Réponse

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":"qwen3.8-max","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":"qwen3.8-max","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":"qwen3.8-max","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: [DONE]

DashScope

Étant donné que l'API DashScope pour la série Qwen3.5 utilise une interface multimodale, l'exemple suivant renvoie une url error . Pour une utilisation correcte, consultez Activer ou désactiver le mode de raisonnement .

Python

Exemple de code

import os
from dashscope import MultiModalConversation
import dashscope

# Configurations vary by region. Modify this value based on your region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1"

# Initialize request parameters
messages = [{"role": "user", "content": [{"text": "Who are you?"}]}]

completion = MultiModalConversation.call(
    # If an environment variable is not configured, replace the following line with your Model Studio API key: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.8-max",
    messages=messages,
    enable_thinking=True,
    stream=True,
    incremental_output=True,
)

# Full thinking process
reasoning_content = ""
# Full response
answer_content = ""
# Tracks if the response phase has started.
is_answering = False

print("=" * 20 + "Thinking process" + "=" * 20)

for chunk in completion:
    # If both the thinking and response content are empty, ignore the chunk.
    content = chunk.output.choices[0].message.content
    reasoning = chunk.output.choices[0].message.reasoning_content
    if not content and reasoning == "":
        pass
    else:
        # If the current chunk is part of the thinking process.
        if reasoning != "" and not content:
            print(reasoning, end="", flush=True)
            reasoning_content += reasoning
        # If the current chunk is part of the response.
        elif content:
            if not is_answering:
                print("\n" + "=" * 20 + "Full response" + "=" * 20)
                is_answering = True
            print(content[0]["text"], end="", flush=True)
            answer_content += content[0]["text"]

# To print the full thinking process and full response, uncomment the following code.
# print("=" * 20 + "Full thinking process" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "Full response" + "=" * 20 + "\n")
# print(f"{answer_content}")

Réponse

====================Thinking process====================
To answer the query "Who are you?", the response must state my identity as Qwen, a large language model from Alibaba Cloud. It will then explain my purpose as a helpful assistant by outlining key functions like question answering, text generation, and logical reasoning. The response will maintain a conversational tone, avoiding jargon. To encourage further engagement, it will end with an open-ended question. Finally, I'll check for clarity, conciseness, and a balance between a friendly and professional tone.
====================Full response====================
Hello! I am Qwen, a large-scale language model developed by Alibaba Cloud. I can answer questions, generate text, perform logical reasoning, write code, and more, to provide help and support. Whether you have a question about daily life or a professional topic, I will do my best to help. Is there anything I can help you with?

Java

Exemple de code

// The version of the DashScope SDK must be 2.19.4 or later.
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // The following base_url is for the Singapore region. If you use a model in the Virginia region, you must change the base_url to https://dashscope-us.aliyuncs.com/api/v1.
        // Configurations vary by region. Modify the configuration based on your actual region.
        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 handleMultiModalConversationResult(MultiModalConversationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();
        String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get("text") : "";

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================Thinking Process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Complete Response====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {
        return MultiModalConversationParam.builder()
                 // API keys vary by region. To obtain an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key
                // If you have not configured the environment variable, replace the following line with your Alibaba Cloud Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen3.8-max")
                .enableThinking(true)
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {
        MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(message -> handleMultiModalConversationResult(message));
    }

    public static void main(String[] args) {
        try {
            MultiModalConversation conv = new MultiModalConversation();
            MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap("text", "Who are you?"))).build();
            streamCallWithMessage(conv, userMsg);
//             Print the final result.
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================Complete Response====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

Réponse

====================Thinking process====================
The response to "Who are you?" must be based on my predefined identity as Qwen, a large language model from Alibaba Cloud. The answer will be conversational, concise, and easy to understand. It will first state my identity, then explain my functions, including text creation, logical reasoning, coding, and multilingual support. The tone will be friendly, and the response will end with an invitation for the user to ask for help, to encourage further interaction.
====================Full response====================
Hello! I am Qwen, a large language model from Alibaba Group. I can answer questions; create text such as stories, official documents, emails, and scripts; perform logical reasoning; write code; express opinions; and even play games. I am proficient in multiple languages, including but not limited to Chinese, English, German, French, and Spanish. Is there anything I can help you with?

HTTP

Exemple de code

curl

# ======= Important =======
# API keys vary by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The following is the URL for the Singapore region. For the China (Beijing) region, replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# For the US (Virginia) region, replace the URL with: https://dashscope-us.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation
# === Remove this comment before execution ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.8-max",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [{"text": "Who are you?"}]
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

Réponse

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Hmm","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":"user","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":"asks","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":"help","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":"Please feel free","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":"to","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":"let me know","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"}

Fonctionnalités principales

Basculer entre les modes avec et sans raisonnement

Le mode de raisonnement améliore la qualité des réponses, mais augmente la latence et le coût. Sur les modèles à raisonnement hybride, activez-le ou désactivez-le pour chaque requête selon la complexité de la demande :

  • Définissez enable_thinking sur false pour les requêtes simples (conversation informelle, questions-réponses directes).
  • Définissez enable_thinking sur true pour les tâches nécessitant un raisonnement complexe (problèmes logiques, génération de code ou calculs mathématiques).

Compatible OpenAI

Importantenable_thinking n'est pas un paramètre standard OpenAI. Dans le SDK Python OpenAI, transmettez-le via extra_body. Dans le SDK Node.js, passez-le en tant que paramètre de premier niveau.

Python

Exemple de code

from openai import OpenAI
import os

# Initialize the OpenAI client.
client = OpenAI(
    # If the environment variable is not configured, replace the value with your Model Studio API key: api_key="sk-xxx"
    # API keys differ by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you?"}]
completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=messages,
    # Set enable_thinking in extra_body to enable the reasoning process.
    extra_body={"enable_thinking": True},
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Full reasoning process
answer_content = ""  # Full response
is_answering = False  # Indicates if the response phase has started
print("\n" + "=" * 20 + "Reasoning process" + "=" * 20 + "\n")

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

    delta = chunk.choices[0].delta

    # Collect only the reasoning content.
    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

    # When content is received, start the response.
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Réponse

====================Reasoning process====================

The user is asking "Who are you?". I need to determine what they want to know. They might be interacting with me for the first time or want to confirm my identity. I should introduce myself as Qwen, developed by Tongyi Lab. Then, I should explain my capabilities, such as answering questions, creating text, and coding, so the user understands how I can assist them. I should also mention my multilingual support so international users know they can communicate in different languages. Finally, I should maintain a friendly tone and invite them to ask questions to encourage further interaction. The explanation must be clear and simple, avoiding technical jargon. The user likely wants a quick overview of my abilities, so I will focus on my functions and applications. I should also consider if any information is missing, such as mentioning Alibaba Group or more technical details. However, the user probably only needs basic information. I will ensure the response is friendly and professional, and encourages them to continue the conversation.
====================Full response====================

I am Qwen, a large-scale language model developed by Tongyi Lab. I can help you answer questions, create text, code, and express opinions. I support communication in multiple languages. How can I help you?
====================Token usage====================

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

Exemple de code

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

// Initialize the OpenAI client.
const openai = new OpenAI({
    // If the environment variable is not configured, replace the value with your Model Studio API key: apiKey: "sk-xxx"
    apiKey: process.env.DASHSCOPE_API_KEY,
    // Configurations vary by region. Modify this based on your actual region.
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

let reasoningContent = ''; // Full reasoning process
let answerContent = ''; // Full response
let isAnswering = false; // Indicates if the response phase has started

async function main() {
    try {
        const messages = [{ role: 'user', content: 'Who are you?' }];

        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            // In the Node.js SDK, non-standard parameters such as enable_thinking are passed as top-level properties and are not required in extra_body.
            enable_thinking: true,
            stream: true,
            stream_options: {
                include_usage: true
            },
        });

        console.log('\n' + '='.repeat(20) + 'Reasoning process' + '='.repeat(20) + '\n');

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

            const delta = chunk.choices[0].delta;

            // Collect only the reasoning content.
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // When content is received, start the response.
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + 'Full response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Réponse

====================Reasoning process====================

The user is asking "Who are you?". I need to determine what they want to know. They might be interacting with me for the first time or want to confirm my identity. I should introduce myself as Qwen, and mention my English name is also Qwen. Then, I will state that I am a large-scale language model independently developed by Tongyi Lab at Alibaba Group. Next, I should list my capabilities, such as answering questions, creating text, coding, and expressing opinions, so the user understands my purpose. I should also mention my multilingual support, which international users will find useful. Finally, I will invite them to ask questions with a friendly and open attitude. I must use simple, easy-to-understand language and avoid excessive technical jargon. The user may need help or just be curious, so the response should be welcoming and encourage further interaction. I should also consider if the user has deeper needs, such as testing my abilities or seeking specific help, but the initial response will focus on basic information and guidance. I will keep the tone conversational and use simple sentences for effective communication.
====================Full response====================

Hello! I am Qwen. I am a large-scale language model independently developed by Tongyi Lab at Alibaba Group. I can help you answer questions, create text such as stories, official documents, emails, and scripts, perform logical reasoning, code, and even express opinions and play games. I support multiple languages, including but not limited to Chinese, English, German, French, and Spanish.

If you have any questions or need help, feel free to ask!
====================Token usage====================

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

HTTP

Exemple de code

curl

# ======= IMPORTANT =======
# API keys differ by region. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The base_url varies by region. For more information, see https://www.alibabacloud.com/help/en/model-studio/regions/
# === Delete this comment before execution ===
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.8-max",
    "messages": [
        {
            "role": "user",
            "content": "Who are you?"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true
}'

DashScope

L'API DashScope pour la série Qwen3.5 utilise une interface multimodale. Les exemples suivants renvoient une url error . Pour une utilisation correcte, consultez Activer ou désactiver le mode de raisonnement .

Python

Exemple de code

import os
from dashscope import MultiModalConversation
import dashscope

# Configurations vary by region. Modify this as needed.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

# Initialize request parameters.
messages = [{"role": "user", "content": [{"text": "Who are you?"}]}]

completion = MultiModalConversation.call(
    # If you have not set an environment variable, replace this with your Model Studio API key: api_key="sk-xxx"
    # API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/regions
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.8-max",
    messages=messages,
    enable_thinking=True,     # Enable the thinking process.
    stream=True,              # Enable streaming output.
    incremental_output=True,  # Enable incremental output.
)

reasoning_content = ""  # Full thinking process
answer_content = ""     # Full response
is_answering = False    # Indicates if the model is in the answering phase.

print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

for chunk in completion:
    message = chunk.output.choices[0].message

    # Collect only the thinking content.
    if message.reasoning_content:
        if not is_answering:
            print(message.reasoning_content, end="", flush=True)
        reasoning_content += message.reasoning_content

    # When content is received, start building the response.
    if message.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Full response" + "=" * 20 + "\n")
            is_answering = True
        print(message.content[0]["text"], end="", flush=True)
        answer_content += message.content[0]["text"]

print("\n" + "=" * 20 + "Token usage" + "=" * 20 + "\n")
print(chunk.usage)
# After the loop, the reasoning_content and answer_content variables contain the complete content.
# You can perform subsequent processing here as needed.
# print(f"\n\nFull thinking process:\n{reasoning_content}")
# print(f"\nFull response:\n{answer_content}")

Réponse

====================Thinking process====================

Okay, the user is asking "Who are you?". I need to figure out what they want to know. They might be new to me or just want to confirm my identity. First, I should introduce myself as Qwen and state that I am a large-scale language model from Tongyi Lab. Then, I should explain my capabilities, such as answering questions, writing text, and coding, so the user knows what I can do. I should also mention my multilingual support for international users. Finally, I will be friendly and invite them to ask more questions to encourage interaction. It is important to use simple language and avoid technical jargon. The user might have other needs, like testing my abilities or getting help, so providing specific examples like writing stories, official documents, or emails would be helpful. I also need to make sure the response is well-structured. I can list my functions, but a natural flow might be better than bullets. I must also clarify that I am an AI assistant without personal consciousness and that my answers are based on training data to prevent misunderstandings. I should check if I missed any important details, like my multimodal capabilities or recent updates, but it is probably not necessary to go into too much detail for a first response. In short, the answer should be comprehensive but concise, friendly, and helpful, making the user feel understood and supported.
====================Full response====================

I am Qwen, a large-scale language model developed by Tongyi Lab of Alibaba Group. I can help you with the following:

1. **Answering questions**: I can try to answer your academic, general knowledge, or domain-specific questions.
2. **Creating text**: I can help you write stories, official documents, emails, scripts, and more.
3. **Logical reasoning**: I can help you with logical reasoning and problem-solving.
4. **Programming**: I can understand and generate code in various programming languages.
5. **Multilingual support**: I support multiple languages, including but not limited to Chinese, English, German, French, and Spanish.

If you have any questions or need help, feel free to let me know!
====================Token usage====================

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

Java

Exemple de code

// Requires DashScope SDK v2.19.4 or later.
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import java.util.Collections;
import java.util.List;
import java.util.Map;
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 com.alibaba.dashscope.exception.UploadFileException;
import io.reactivex.Flowable;
import java.lang.System;
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class Main {
    static {
        // The base HTTP API URL varies by region. Modify it according to your region.
        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 handleMultiModalConversationResult(MultiModalConversationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();
        String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get("text") : "";

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================Thinking process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Full response====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {
        return MultiModalConversationParam.builder()
                // If you have not set an environment variable, replace the next line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen3.8-max")
                .enableThinking(true)
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {
        MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(message -> handleMultiModalConversationResult(message));
    }

    public static void main(String[] args) {
        try {
            MultiModalConversation conv = new MultiModalConversation();
            MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap("text", "Who are you?"))).build();
            streamCallWithMessage(conv, userMsg);
//             Print the final result.
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================Full response====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

Réponse

====================Thinking process====================
Okay, the user is asking "Who are you?". I need to figure out what they want to know. They might want to know my identity or are just testing my response. First, I should clearly state that I am Qwen, a large-scale language model from Alibaba Group. Then, I should briefly introduce my capabilities, such as answering questions, writing text, and coding, so the user understands what I can do. I should also mention that I support multiple languages so international users know they can communicate with me in different languages. Finally, I will be friendly and invite them to ask questions to make them feel comfortable and willing to interact further. The answer should not be too long but should be comprehensive. The user might have follow-up questions about my technical details or use cases, but the initial answer should be simple and clear. I will make sure not to use technical jargon so all users can understand. I will check for any missing important information, such as multilingual support and specific examples of my functions. Okay, this should cover the user's needs.
====================Full response====================
I am Qwen, a large-scale language model from Alibaba Group. I can answer questions, create text (such as stories, official documents, emails, and scripts), perform logical reasoning, code, express opinions, and play games. I also support multilingual communication, including but not limited to Chinese, English, German, French, and Spanish. If you have any questions or need help, feel free to let me know!

HTTP

Exemple de code

curl

# ======= IMPORTANT =======
# API keys are region-specific. To get an API key, see https://www.alibabacloud.com/help/en/model-studio/get-api-key
# The base_url varies by region. Modify it as needed.
# === Delete this comment before running ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.8-max",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [{"text": "Who are you?"}]
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

Réponse

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Hmm","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":"user","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":" asks","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":"help","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":" feel free","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":" to","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":" let me know","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"}

Pour les modèles open source à raisonnement hybride Qwen3, ainsi que pour qwen-plus-2025-04-28 et les modèles associés, vous pouvez également contrôler le mode de raisonnement via des suffixes d'invite. Lorsque enable_thinking est défini sur true, ajoutez /no_think à une invite pour désactiver le raisonnement lors de ce tour, ou ajoutez /think pour le réactiver. Le modèle respecte toujours la dernière instruction /think ou /no_think reçue.

Limiter la longueur du raisonnement

Les traces de raisonnement augmentent la latence et le coût en tokens. Utilisez thinking_budget pour plafonner le nombre de tokens consacrés au raisonnement. Une fois cette limite atteinte, le modèle interrompt son raisonnement et répond immédiatement. Ce paramètre s'applique aux modèles Qwen3.8, Qwen3.7, Qwen3.6, Qwen3.5, Qwen3-VL, Qwen3, GLM et Kimi .

La valeur par défaut de thinking_budget correspond à la longueur maximale de chaîne de pensée du modèle. Consultez la page console de chaque modèle pour connaître sa valeur par défaut.

OpenAI compatible

Python

Exemple de code

from openai import OpenAI
import os

# Initialize the OpenAI client.
client = OpenAI(
    # If the environment variable is not configured, replace "sk-xxx" with your Model Studio API key.
    # API keys are region-specific. To get an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key.
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Configurations vary by region. Modify the base_url according to your region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

messages = [{"role": "user", "content": "Who are you"}]

completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=messages,
    # The enable_thinking parameter enables the thinking process, and thinking_budget sets its token limit.
    extra_body={
        "enable_thinking": True,
        "thinking_budget": 50
        },
    stream=True,
    stream_options={
        "include_usage": True
    },
)

reasoning_content = ""  # Complete thinking process
answer_content = ""  # Complete response
is_answering = False  # Tracks if the response phase has started
print("\n" + "=" * 20 + "Thinking process" + "=" * 20 + "\n")

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

    delta = chunk.choices[0].delta

    # Collect only the thinking content.
    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

    # When content is received, the response phase begins.
    if hasattr(delta, "content") and delta.content:
        if not is_answering:
            print("\n" + "=" * 20 + "Complete response" + "=" * 20 + "\n")
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Réponse

====================Thinking process====================

Okay, the user is asking, "Who are you?" I need to provide a clear and friendly response. First, I should state my identity as Qwen, developed by Tongyi Lab at Alibaba Group. Next, I need to explain my main functions, such as answering
====================Complete response====================

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can answer questions, create text, perform logical reasoning, and write code.

Node.js

Exemple de code

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

// Initialize the OpenAI client.
const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY, // Read from an environment variable.
    // Configurations vary by region. Modify the baseURL according to your region.
    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: 'Who are you' }];
        const stream = await openai.chat.completions.create({
            model: 'qwen-plus',
            messages,
            stream: true,
            // The enable_thinking parameter enables the thinking process, and thinking_budget sets its token limit.
            enable_thinking: true,
            thinking_budget: 50
        });
        console.log('\n' + '='.repeat(20) + 'Thinking process' + '='.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;

            // Collect only the thinking content.
            if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
                if (!isAnswering) {
                    process.stdout.write(delta.reasoning_content);
                }
                reasoningContent += delta.reasoning_content;
            }

            // When content is received, the response phase begins.
            if (delta.content !== undefined && delta.content) {
                if (!isAnswering) {
                    console.log('\n' + '='.repeat(20) + 'Complete response' + '='.repeat(20) + '\n');
                    isAnswering = true;
                }
                process.stdout.write(delta.content);
                answerContent += delta.content;
            }
        }
    } catch (error) {
        console.error('Error:', error);
    }
}

main();

Réponse

====================Thinking process====================

Okay, the user is asking, "Who are you?" I need to provide a clear and accurate response. First, I should state my identity as Qwen, developed by Tongyi Lab at Alibaba Group. Next, I should explain my main functions, such as answering questions
====================Complete response====================

I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can answer questions, create text, perform logical reasoning, and write code.

HTTP

Exemple de code

curl

# ======= Important =======
# The following is the base URL for the Singapore region. For models in the China (Beijing) region, replace the URL with: https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# For models in the US (Virginia) region, replace the URL with: https://dashscope-us.aliyuncs.com/compatible-mode/v1/chat/completions
# === Remove this comment before execution ===
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.8-max",
    "messages": [
        {
            "role": "user",
            "content": "Who are you"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true,
    "thinking_budget": 50
}'

Réponse

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":"qwen3.8-max","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":"qwen3.8-max","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":"qwen3.8-max","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}

data: [DONE]

DashScope

L'API DashScope pour la série Qwen3.5 utilise une interface multimodale. L'exemple suivant renvoie une url error . Pour une utilisation correcte, consultez Activer ou désactiver le mode de raisonnement .

Python

Exemple de code

import os
from dashscope import MultiModalConversation
import dashscope

# The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

messages = [{"role": "user", "content": [{"text": "Who are you?"}]}]

completion = MultiModalConversation.call(
    # If the environment variable is not configured, replace the following line with your Model Studio API key: api_key = "sk-xxx",
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.8-max",
    messages=messages,
    enable_thinking=True,
    # Sets the token limit for the thinking process.
    thinking_budget=50,
    stream=True,
    incremental_output=True,
)

# Stores the complete thinking process.
reasoning_content = ""
# Stores the complete response.
answer_content = ""
# Tracks if the response phase has started.
is_answering = False

print("=" * 20 + "Thinking process" + "=" * 20)

for chunk in completion:
    # Ignore chunks where both thinking content and response content are empty.
    content = chunk.output.choices[0].message.content
    reasoning = chunk.output.choices[0].message.reasoning_content
    if not content and reasoning == "":
        pass
    else:
        # If the current chunk contains thinking content.
        if reasoning != "" and not content:
            print(reasoning, end="", flush=True)
            reasoning_content += reasoning
        # If the current chunk contains response content.
        elif content:
            if not is_answering:
                print("\n" + "=" * 20 + "Complete response" + "=" * 20)
                is_answering = True
            print(content[0]["text"], end="", flush=True)
            answer_content += content[0]["text"]

# To print the complete thinking process and response, uncomment and run the following code.
# print("=" * 20 + "Complete thinking process" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "Complete response" + "=" * 20 + "\n")
# print(f"{answer_content}")

Réponse

====================Thinking process====================
Okay, the user is asking, "Who are you?" I need to provide a clear and friendly response. First, I must introduce myself as Qwen, developed by Tongyi Lab at Alibaba Group. Next, I should explain my main functions, such as
====================Complete response====================
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can answer questions, create text, perform logical reasoning, and write code.

Java

Exemple de code

// The DashScope SDK version must be 2.19.4 or later.
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversation;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationParam;
import com.alibaba.dashscope.aigc.multimodalconversation.MultiModalConversationResult;
import com.alibaba.dashscope.common.MultiModalMessage;
import java.util.Collections;
import java.util.List;
import java.util.Map;
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 com.alibaba.dashscope.exception.UploadFileException;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;

public class Main {
    static {
        // The base HTTP API URL varies by region. Modify it according to your region.
        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 handleMultiModalConversationResult(MultiModalConversationResult message) {
        String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
        List<Map<String, Object>> contentList = (List<Map<String, Object>>) message.getOutput().getChoices().get(0).getMessage().getContent();
        String content = (contentList != null && !contentList.isEmpty()) ? (String) contentList.get(0).get("text") : "";

        if (!reasoning.isEmpty()) {
            reasoningContent.append(reasoning);
            if (isFirstPrint) {
                System.out.println("====================Thinking process====================");
                isFirstPrint = false;
            }
            System.out.print(reasoning);
        }

        if (!content.isEmpty()) {
            finalContent.append(content);
            if (!isFirstPrint) {
                System.out.println("\n====================Complete response====================");
                isFirstPrint = true;
            }
            System.out.print(content);
        }
    }
    private static MultiModalConversationParam buildMultiModalConversationParam(MultiModalMessage userMsg) {
        return MultiModalConversationParam.builder()
                // If the environment variable is not configured, replace the following line with your Model Studio API key: .apiKey("sk-xxx")
                .apiKey(System.getenv("DASHSCOPE_API_KEY"))
                .model("qwen3.8-max")
                .enableThinking(true)
                .thinkingBudget(50)
                .incrementalOutput(true)
                .messages(Arrays.asList(userMsg))
                .build();
    }
    public static void streamCallWithMessage(MultiModalConversation conv, MultiModalMessage userMsg)
            throws NoApiKeyException, ApiException, InputRequiredException, UploadFileException {
        MultiModalConversationParam param = buildMultiModalConversationParam(userMsg);
        Flowable<MultiModalConversationResult> result = conv.streamCall(param);
        result.blockingForEach(message -> handleMultiModalConversationResult(message));
    }

    public static void main(String[] args) {
        try {
            MultiModalConversation conv = new MultiModalConversation();
            MultiModalMessage userMsg = MultiModalMessage.builder().role(Role.USER.getValue()).content(Arrays.asList(Collections.singletonMap("text", "Who are you?"))).build();
            streamCallWithMessage(conv, userMsg);
//             Print the final result.
//            if (reasoningContent.length() > 0) {
//                System.out.println("\n====================Complete response====================");
//                System.out.println(finalContent.toString());
//            }
        } catch (ApiException | NoApiKeyException | InputRequiredException | UploadFileException e) {
            logger.error("An exception occurred: {}", e.getMessage());
        }
        System.exit(0);
    }
}

Réponse

====================Thinking process====================
Okay, the user is asking, "Who are you?" I need to provide a clear and friendly response. First, I must introduce myself as Qwen, developed by Tongyi Lab at Alibaba Group. Next, I should explain my main functions, such as
====================Complete response====================
I am Qwen, a large-scale language model developed by Tongyi Lab at Alibaba Group. I can answer questions, create text, perform logical reasoning, and write code.

HTTP

Exemples de code

curl

# ======= Important =======
# API keys are region-specific. To get an API key, visit https://www.alibabacloud.com/help/en/model-studio/get-api-key.
# The endpoint URL varies by region. Modify it according to your region.
# === Remove this comment before execution ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.8-max",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [{"text": "Who are you?"}]
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "thinking_budget": 50,
        "incremental_output": true,
        "result_format": "message"
    }
}'

Réponse

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"Okay","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"}

Transmission du processus de réflexion

Par défaut, le modèle ignore le champ reasoning_content présent dans l'historique des messages. Définissez preserve_thinking sur true pour transmettre le raisonnement précédent aux tours suivants. Le contenu de reasoning_content issu des messages antérieurs de l'assistant est alors ajouté à l'entrée du modèle.

ImportantLe paramètre preserve_thinking est uniquement pris en charge pour les modèles qwen3.8-max, qwen3.7-max, qwen3.7-max-us, 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-us, qwen3.7-plus-2026-05-26, qwen3.6-plus, qwen3.6-plus-2026-04-02, qwen3.7-flash, qwen3.7-flash-2026-07-15, kimi-k2.7-code (déployé sur Alibaba Cloud Model Studio), kimi-k2.6 (déployé sur Alibaba Cloud Model Studio), kimi/kimi-k3 (déployé sur Moonshot AI), kimi/kimi-k2.7-code-highspeed (déployé sur Moonshot AI), kimi/kimi-k2.7-code (déployé sur Moonshot AI) et kimi/kimi-k2.6 (déployé sur Moonshot AI).

L'activation de ce paramètre ne provoque aucune erreur si les messages de l'historique ne contiennent pas de champ reasoning_content .

Lorsque cette option est activée, le contenu de reasoning_content provenant de l'historique de conversation est comptabilisé dans les tokens d'entrée et la facturation.

Compatible OpenAI

Remarquepreserve_thinking n'est pas un paramètre standard OpenAI. Lors de l'utilisation du SDK Python, transmettez ce paramètre via extra_body.

Python

Exemples de code

from openai import OpenAI
import os

client = OpenAI(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # Configurations vary by region. Modify this based on your actual region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

# First turn of the conversation
messages = [
    {"role": "user", "content": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."}
]

first_reasoning = ""
first_content = ""
is_answering = False

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

print("=" * 20 + "First-turn thought process" + "=" * 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 + "First-turn response" + "=" * 20)
            is_answering = True
        print(delta.content, end="", flush=True)
        first_content += delta.content

# Second turn: Pass the thought process and ask why the model excluded Kafka
messages = [
    {"role": "user", "content": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."},
    {
        "role": "assistant",
        "content": first_content,
        "reasoning_content": first_reasoning,
    },
    {"role": "user", "content": "Why did you exclude Kafka in your comparison?"},
]

reasoning_content = ""
answer_content = ""
is_answering = False

# Pass preserve_thinking through extra_body
completion = client.chat.completions.create(
    model="qwen3.8-max",
    messages=messages,
    extra_body={
        "enable_thinking": True,
        "preserve_thinking": True,
    },
    stream=True,
    stream_options={"include_usage": True},
)

print("\n" + "=" * 20 + "Second-turn thought process" + "=" * 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 + "Second-turn response" + "=" * 20)
            is_answering = True
        print(delta.content, end="", flush=True)
        answer_content += delta.content

Réponse

====================First-turn thought process====================
The user needs a message queue for an E-commerce system with tens of millions of daily messages. I will compare mainstream solutions based on dimensions such as throughput, reliability, delayed messages, and transaction support...

RocketMQ: Validated in Alibaba's E-commerce scenarios, natively supports transactional and delayed messages, and provides strict partition-level ordering...
Kafka: Extremely high throughput, but lacks native support for transactional and delayed messages, requiring custom compensation mechanisms...
RabbitMQ: Low latency, but limited cluster scalability, with a peak TPS in the tens of thousands...
====================First-turn response====================
Considering the core needs of an E-commerce scenario (transactional messages, delayed messages, ordering, and peak handling), I recommend Apache RocketMQ. If your team already has a Kafka ecosystem or requires strong real-time analytics, Kafka is also a viable option.
====================Second-turn thought process====================
The user is asking why Kafka was excluded. Reviewing my historical thought process, I did not exclude Kafka; I gave it a 4-star rating. I will refer to my previous detailed comparison to explain...

In the last turn, I compared the differences between RocketMQ and Kafka regarding transactional messages, delayed messages, and ordering. Kafka's main disadvantage is that it requires additional architectural design to compensate for E-commerce-specific semantics...
====================Second-turn response====================
I did not exclude Kafka. Kafka excels in throughput and ecosystem. The reason RocketMQ received a slightly higher rating is its better out-of-the-box match for core E-commerce workflows. RocketMQ natively supports transactional and delayed messages, while Kafka requires self-implementation through architectural patterns like the Outbox Pattern. If your team already has a Kafka ecosystem, it is fully capable of handling a scenario with tens of millions of messages.

Node.js

Exemples de code

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

const openai = new OpenAI({
    apiKey: process.env.DASHSCOPE_API_KEY,
    // Configurations vary by region. Modify this based on your actual region.
    baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});

async function main() {
    // First turn of the conversation
    let firstReasoning = '';
    let firstContent = '';
    let isAnswering = false;

    const stream1 = await openai.chat.completions.create({
        model: 'qwen3.7-plus',
        messages: [{ role: 'user', content: 'I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation.' }],
        stream: true,
        enable_thinking: true
    });

    console.log('='.repeat(20) + 'First-turn thought process' + '='.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) + 'First-turn response' + '='.repeat(20));
                isAnswering = true;
            }
            process.stdout.write(delta.content);
            firstContent += delta.content;
        }
    }

    // Second turn: Pass the thought process
    let reasoningContent = '';
    let answerContent = '';
    isAnswering = false;

    const stream2 = await openai.chat.completions.create({
        model: 'qwen3.7-plus',
        messages: [
            { role: 'user', content: 'I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation.' },
            {
                role: 'assistant',
                content: firstContent,
                reasoning_content: firstReasoning
            },
            { role: 'user', content: 'Why did you exclude Kafka in your comparison?' }
        ],
        stream: true,
        enable_thinking: true,
        // Pass preserve_thinking as a top-level parameter
        preserve_thinking: true
    });

    console.log('\n' + '='.repeat(20) + 'Second-turn thought process' + '='.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) + 'Second-turn response' + '='.repeat(20));
                isAnswering = true;
            }
            process.stdout.write(delta.content);
            answerContent += delta.content;
        }
    }
}

main();

Réponse

====================First-turn thought process====================
The user needs a message queue for an E-commerce system with tens of millions of daily messages. I will compare mainstream solutions based on dimensions such as throughput, reliability, delayed messages, and transaction support...
====================First-turn response====================
Considering the core needs of an E-commerce scenario, I recommend Apache RocketMQ. If your team already has a Kafka ecosystem, Kafka is also a viable option.
====================Second-turn thought process====================
The user is asking why Kafka was excluded. Referring to my previous thought process, I did not exclude Kafka...
====================Second-turn response====================
I did not exclude Kafka. Kafka excels in throughput and ecosystem. The reason RocketMQ received a slightly higher rating is its better out-of-the-box match for core E-commerce workflows.

HTTP

Exemples de code

curl

# The base_url varies by region. Modify it based on your actual region.
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.8-max",
    "messages": [
        {
            "role": "user",
            "content": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."
        },
        {
            "role": "assistant",
            "content": "Considering the core needs of an E-commerce scenario, I recommend Apache RocketMQ.",
            "reasoning_content": "The user needs a message queue for an E-commerce system with tens of millions of daily messages. RocketMQ natively supports transactional and delayed messages, making it more suitable for E-commerce scenarios. Kafka has extremely high throughput but requires custom compensation mechanisms."
        },
        {
            "role": "user",
            "content": "Why did you exclude Kafka in your comparison?"
        }
    ],
    "stream": true,
    "stream_options": {
        "include_usage": true
    },
    "enable_thinking": true,
    "preserve_thinking": true
}'

Réponse

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.8-max","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.8-max","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.8-max","id":"chatcmpl-example-001"}

data: [DONE]

DashScope

RemarqueLe SDK Java ne prend pas encore en charge le paramètre preserve_thinking. Pour les appels HTTP, placez le paramètre preserve_thinking dans l'objet parameters.

Python

Exemples de code

import os
from dashscope import MultiModalConversation
import dashscope

# The following URL is for the Singapore region. When calling, replace WorkspaceId with your actual workspace ID. URLs vary by region.
dashscope.base_http_api_url = "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/"

# First turn of the conversation
messages = [
    {"role": "user", "content": [{"text": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."}]}
]

first_reasoning = ""
first_content = ""
is_answering = False

completion = MultiModalConversation.call(
    # If the environment variable is not set, replace the next line with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.8-max",
    messages=messages,
    enable_thinking=True,
    stream=True,
    incremental_output=True,
)

print("=" * 20 + "First-turn thought process" + "=" * 20)

for chunk in completion:
    content = chunk.output.choices[0].message.content
    reasoning = chunk.output.choices[0].message.reasoning_content
    if not content and reasoning == "":
        pass
    else:
        if reasoning != "" and not content:
            print(reasoning, end="", flush=True)
            first_reasoning += reasoning
        elif content:
            if not is_answering:
                print("\n" + "=" * 20 + "First-turn response" + "=" * 20)
                is_answering = True
            print(content[0]["text"], end="", flush=True)
            first_content += content[0]["text"]

# Second turn: Pass the thought process
messages = [
    {"role": "user", "content": [{"text": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."}]},
    {
        "role": "assistant",
        "content": [{"text": first_content}],
        "reasoning_content": first_reasoning,
    },
    {"role": "user", "content": [{"text": "Why did you exclude Kafka in your comparison?"}]},
]

reasoning_content = ""
answer_content = ""
is_answering = False

completion = MultiModalConversation.call(
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    model="qwen3.8-max",
    messages=messages,
    enable_thinking=True,
    # Pass the thought process
    preserve_thinking=True,
    stream=True,
    incremental_output=True,
)

print("\n" + "=" * 20 + "Second-turn thought process" + "=" * 20)

for chunk in completion:
    content = chunk.output.choices[0].message.content
    reasoning = chunk.output.choices[0].message.reasoning_content
    if not content and reasoning == "":
        pass
    else:
        if reasoning != "" and not content:
            print(reasoning, end="", flush=True)
            reasoning_content += reasoning
        elif content:
            if not is_answering:
                print("\n" + "=" * 20 + "Second-turn response" + "=" * 20)
                is_answering = True
            print(content[0]["text"], end="", flush=True)
            answer_content += content[0]["text"]

): 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 + "Second-turn response" + "=" 20) is_answering = True print(chunk.output.choices[0].message.content, end="", flush=True) answer_content += chunk.output.choices[0].message.content

Réponse

====================First-turn thought process====================
The user needs a message queue for an E-commerce system with tens of millions of daily messages. I will compare mainstream solutions based on dimensions such as throughput, reliability, delayed messages, and transaction support...
====================First-turn response====================
Considering the core needs of an E-commerce scenario, I recommend Apache RocketMQ. If your team already has a Kafka ecosystem, Kafka is also a viable option.
====================Second-turn thought process====================
The user is asking why Kafka was excluded. Referring to my previous thought process, I did not exclude Kafka...
====================Second-turn response====================
I did not exclude Kafka. Kafka excels in throughput and ecosystem. The reason RocketMQ received a slightly higher rating is its better out-of-the-box match for core E-commerce workflows.

HTTP

Exemples de code

curl

# The base_url varies by region. Modify it based on your actual region.
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/multimodal-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
    "model": "qwen3.8-max",
    "input":{
        "messages":[
            {
                "role": "user",
                "content": [{"text": "I need to choose a message queue for an E-commerce system that handles tens of millions of messages per day. Please provide a recommendation."}]
            },
            {
                "role": "assistant",
                "content": [{"text": "Considering the core needs of an E-commerce scenario, I recommend Apache RocketMQ."}],
                "reasoning_content": "The user needs a message queue for an E-commerce system with tens of millions of daily messages. RocketMQ natively supports transactional and delayed messages, making it more suitable for E-commerce scenarios. Kafka has extremely high throughput but requires custom compensation mechanisms."
            },
            {
                "role": "user",
                "content": [{"text": "Why did you exclude Kafka in your comparison?"}]
            }
        ]
    },
    "parameters":{
        "enable_thinking": true,
        "preserve_thinking": true,
        "incremental_output": true,
        "result_format": "message"
    }
}'

Réponse

id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"user"},"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":"follow-up"},"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"}

Autres fonctionnalités

Facturation

  • Le contenu de réflexion est facturé par token de sortie.

  • Certains modèles à réflexion hybride appliquent des tarifs différents selon que le mode réflexion est activé ou non.

    Si un modèle en mode réflexion ne produit aucun résultat de raisonnement, la tarification hors réflexion s'applique.

FAQ

Q : Comment désactiver le mode réflexion ?

La procédure dépend du type de modèle :

  • Pour les modèles à réflexion hybride, tels que qwen-plus et deepseek-v4-pro, définissez enable_thinking sur false.
  • Pour les modèles exclusivement dédiés à la réflexion, comme glm-5.3 et kimi-k3, il est impossible de désactiver ce mode.

Q : Comment appeler un modèle de réflexion en mode non-streaming (synchrone) ?

Les exemples de cette rubrique utilisent le streaming par défaut (recommandé pour observer le raisonnement en temps réel et éviter une longue attente). Les modèles de réflexion commerciaux (tels que qwen-plus e qwen-flash) prennent également en charge la sortie non-streaming (synchrone), qui retourne l'intégralité du raisonnement et de la réponse en une seule fois.

Lors du passage d'un exemple du mode streaming au mode non-streaming, mettez également à jour le code d'analyse de la réponse : un appel non-streaming retourne un objet de réponse complet ( completion ). Ne l'itérez pas avec for chunk in completion comme dans l'exemple streaming (cela déclenche l'erreur 'tuple' object has no attribute 'choices' ). Lisez plutôt directement completion.choices[0].message.reasoning_content (raisonnement) et completion.choices[0].message.content (réponse). De plus, lorsque stream=False , ne définissez pas le paramètre stream_options .

L'exemple suivant appelle qwen3.8-max en mode réflexion sans streaming, via l'interface compatible OpenAI :

from openai import OpenAI
import os

client = OpenAI(
    # API keys differ by region. Get an API key: https://www.alibabacloud.com/help/en/model-studio/get-api-key
    # If the environment variable is not configured, replace the line below with your Model Studio API key: api_key="sk-xxx"
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # The following is the configuration for the Singapore region. Replace WorkspaceId with your real workspace ID; configurations differ by region.
    base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3.8-max",  # Replace with a thinking model that supports non-streaming output
    messages=[{"role": "user", "content": "Who are you?"}],
    extra_body={"enable_thinking": True},
    stream=False,  # Non-streaming (synchronous) output; do not set stream_options when stream=False
)

# A non-streaming call returns a complete response object. Read message directly; do not iterate.
message = completion.choices[0].message
print("=" * 20 + "Reasoning" + "=" * 20 + "\n")
print(getattr(message, "reasoning_content", "") or "")
print("\n" + "=" * 20 + "Answer" + "=" * 20 + "\n")
print(message.content)

Certains modèles (comme les modèles open source qwen3.5-122b-a10b et qwen3.5-27b) ne prennent en charge que le streaming. Un appel non-streaming retourne l'erreur parameter.enable_thinking only support stream call ; utilisez le streaming pour ces modèles.

Q : Comment acheter des tokens après épuisement de mon quota gratuit ?

Rechargez votre compte dans le centre Dépenses et coûts. Votre compte ne doit présenter aucun impayé pour pouvoir appeler des modèles.

Une fois le quota gratuit épuisé, les appels sont facturés à la minute. Consultez vos dépenses dans Détails de la facture .

Q : Puis-je utiliser des images ou des documents en entrée ?

Ces modèles acceptent uniquement du texte. Qwen3-VL et QVQ prennent en charge la réflexion approfondie sur les images .

Q : Comment consulter la consommation de tokens et le nombre d'appels ?

Une heure après l'appel d'un modèle, accédez à la page Monitoring (Singapore ou Beijing). Définissez les critères de requête, tels que la plage horaire et le workspace. Ensuite, dans la zone Models, localisez le modèle cible et cliquez sur Monitor dans la colonne Actions pour consulter ses statistiques d'appel. Pour plus d'informations, reportez-vous au document Monitoring.

Les données sont actualisées toutes les heures. En période de forte activité, un délai de l'ordre d'une heure peut survenir.

image

Référence API

Pour les paramètres d'entrée et de réponse, consultez Text Generation.

Codes d'erreur

En cas d'échec d'un appel, consultez Error codes.