In real-time chat or long-text generation applications, long wait times degrade user experience and may trigger server-side timeouts, causing tasks to fail. Streaming output addresses these issues by continuously returning fragments of text as the model generates them.
How it works
Streaming output uses the Server-Sent Events (SSE) protocol. After a streaming request starts, the server establishes an HTTP persistent connection with the client. Each time the model generates a text block (called a chunk), it immediately pushes it through this connection. Once all content is generated, the server sends an end signal. The client listens to the event stream and receives and processes text chunks in real time—for example, rendering characters one by one on the interface. This contrasts with non-streaming calls, which return all content at once.Streaming and non-streaming responses differ in structure: non-streaming returns a single JSON object with the text in
choices[0].message.content; streaming returns chunks over SSE with the text in choices[0].delta.content, which the client must concatenate, ending with data: [DONE].Billing
Streaming output uses the same billing rule as non-streaming calls, charging based on the number of input tokens and output tokens in the request. If a request is interrupted, output tokens are counted only for the portion generated before the server received the termination request.How to use
Qwen3 open-source edition, QwQ commercial and open-source editions, QVQ, Qwen3.5-Omni, and Qwen3-Omni-Flash support only streaming output.
Step 1: Configure your API key and select a region
You must have obtained an API key and configured it as an environment variable.
Configuring your API key as an environment variable (DASHSCOPE_API_KEY) is more secure than hard coding it in your code.
Step 2: Make a streaming request
- OpenAI compatible
- DashScope
-
How to enable
Set
streamtotrue. -
View token usage
The OpenAI protocol does not return token usage by default. Set
stream_options={"include_usage": true}so the last returned data chunk includes token usage information.
- Python
- Node.js
- curl
Copy
import os
from openai import OpenAI
# 1. Prepare: Initialize the client
client = OpenAI(
# Configure the API key through an environment variable to avoid hardcoding.
api_key=os.environ["DASHSCOPE_API_KEY"],
# API keys are region-specific. Ensure base_url and the API key use the same region.
# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
# 2. Make a streaming request
completion = client.chat.completions.create(
model="qwen-plus",
messages=[
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "请介绍一下自己"}
],
stream=True,
stream_options={"include_usage": True}
)
# 3. Handle the streaming response
# Collect response chunks in a list; joining at the end is more efficient than repeated string +=
content_parts = []
print("AI: ", end="", flush=True)
for chunk in completion:
if chunk.choices:
content = chunk.choices[0].delta.content or ""
print(content, end="", flush=True)
content_parts.append(content)
elif chunk.usage:
print("\n--- 请求用量 ---")
print(f"输入 Tokens: {chunk.usage.prompt_tokens}")
print(f"输出 Tokens: {chunk.usage.completion_tokens}")
print(f"总计 Tokens: {chunk.usage.total_tokens}")
full_response = "".join(content_parts)
# print(f"\n--- Full response ---\n{full_response}")
Response
Copy
AI: 你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时告诉我!
--- 请求用量 ---
输入 Tokens: 26
输出 Tokens: 87
总计 Tokens: 113
Copy
import OpenAI from "openai";
async function main() {
// 1. Prepare: Initialize the client
// Configure the API key through an environment variable to avoid hardcoding.
if (!process.env.DASHSCOPE_API_KEY) {
throw new Error("请设置环境变量 DASHSCOPE_API_KEY");
}
// API keys are region-specific. Ensure baseURL and the API key use the same region.
// Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
const client = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY,
baseURL: "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
});
try {
// 2. Make a streaming request
const stream = await client.chat.completions.create({
model: "qwen-plus",
messages: [
{ role: "system", content: "You are a helpful assistant." },
{ role: "user", content: "请介绍一下自己" },
],
stream: true,
// Purpose: Get token usage in the last chunk.
stream_options: { include_usage: true },
});
// 3. Handle the streaming response
const contentParts = [];
process.stdout.write("AI: ");
for await (const chunk of stream) {
// The last chunk contains no choices but includes usage information.
if (chunk.choices && chunk.choices.length > 0) {
const content = chunk.choices[0]?.delta?.content || "";
process.stdout.write(content);
contentParts.push(content);
} else if (chunk.usage) {
// Request complete. Print token usage.
console.log("\n--- 请求用量 ---");
console.log(`输入 Tokens: ${chunk.usage.prompt_tokens}`);
console.log(`输出 Tokens: ${chunk.usage.completion_tokens}`);
console.log(`总计 Tokens: ${chunk.usage.total_tokens}`);
}
}
const fullResponse = contentParts.join("");
// console.log(`\n--- Full response ---\n${fullResponse}`);
} catch (error) {
console.error("请求失败:", error);
}
}
main();
Response
Copy
AI: 你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时向我提问!
--- 请求用量 ---
输入 Tokens: 26
输出 Tokens: 89
总计 Tokens: 115
Request
Copy
# ======= Important notes =======
# Ensure the DASHSCOPE_API_KEY environment variable is set
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# For a Beijing model, set base_url to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1/chat/completions
# === Delete this comment before running ===
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" \
--no-buffer \
-d '{
"model": "qwen-plus",
"messages": [
{"role": "user", "content": "你是谁?"}
],
"stream": true,
"stream_options": {"include_usage": true}
}'
Response
The response follows the SSE protocol. Each line starting withdata: represents a data chunk.Copy
data: {"choices":[{"delta":{"content":"","role":"assistant"},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"finish_reason":null,"delta":{"content":"我是"},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"delta":{"content":"来自"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"delta":{"content":"阿里"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"delta":{"content":"云的超大规模语言"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"delta":{"content":"模型,我叫通义千问"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"delta":{"content":"。"},"finish_reason":null,"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[{"finish_reason":"stop","delta":{"content":""},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":22,"completion_tokens":17,"total_tokens":39},"created":1726132850,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-428b414f-fdd4-94c6-b179-8f576ad653a8"}
data: [DONE]
data:: The message payload, usually a JSON string.[DONE]: Indicates the end of the entire streaming response.
-
How to enable
The method to enable streaming output varies by SDK or tool:
- Python SDK: Set the
streamparameter toTrue. - Java SDK: Use the
streamCallinterface. - cURL: Set the header
X-DashScope-SSEtoenable.
- Python SDK: Set the
-
Enable incremental output
The DashScope protocol supports both incremental and non-incremental streaming output:
-
Incremental (recommended): Each data chunk contains only newly generated content. Set
incremental_outputtotrueto enable incremental streaming output (Python SDK 2.0 outputs incrementally by default; you do not need to set this parameter).Example: ["I love","eating","apples"]
-
Non-incremental: Each data chunk contains all previously generated content, wasting network bandwidth and increasing client processing load. Set
incremental_outputtofalseto enable non-incremental streaming output.Example: ["I love","I love eating","I love eating apples"]
-
Incremental (recommended): Each data chunk contains only newly generated content. Set
- View token usage Each data chunk includes real-time token usage information.
- Python
- Java
- curl
Copy
import os
import dashscope
from dashscope import DashScopeError
# 1. Preparation: configure the API key and the client
# It is recommended to configure the API key via an environment variable to avoid hardcoding it.
# The following configuration is for the Singapore (ap-southeast-1) region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
try:
api_key = os.environ["DASHSCOPE_API_KEY"]
except KeyError:
raise ValueError("请设置环境变量 DASHSCOPE_API_KEY")
client = dashscope.Client(api_key=api_key, workspace="{WorkspaceId}", region="ap-southeast-1")
# 2. Send a streaming request
messages = [
{"role": "system", "content": "You are a helpful assistant."},
{"role": "user", "content": "请介绍一下自己"},
]
try:
stream = client.chat.completions.create(
model="qwen-plus",
messages=messages,
stream=True,
# Streaming output is incremental by default: each chunk contains only the newly generated content.
)
# 3. Process the streaming response
content_parts = []
print("AI: ", end="", flush=True)
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content, end="", flush=True)
content_parts.append(delta.content)
# Check whether this is the last chunk (the last chunk contains the token usage)
if chunk.choices[0].finish_reason == "stop":
usage = chunk.usage
print("\n--- 请求用量 ---")
print(f"输入 Tokens: {usage.input_tokens}")
print(f"输出 Tokens: {usage.output_tokens}")
print(f"总计 Tokens: {usage.total_tokens}")
full_response = "".join(content_parts)
# print(f"\n--- Full response ---\n{full_response}")
except DashScopeError as e:
# Handle errors (errors during streaming are raised directly as exceptions)
print(
f"\n请求失败: request_id={e.request_id}, code={e.code}, message={e.message}"
)
Copy
AI: 你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时向我提问!
--- 请求用量 ---
输入 Tokens: 26
输出 Tokens: 91
总计 Tokens: 117
Copy
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import io.reactivex.Flowable;
import io.reactivex.schedulers.Schedulers;
import java.util.Arrays;
import java.util.concurrent.CountDownLatch;
import com.alibaba.dashscope.protocol.Protocol;
public class Main {
public static void main(String[] args) {
// 1. Get an API key
String apiKey = System.getenv("DASHSCOPE_API_KEY");
if (apiKey == null || apiKey.isEmpty()) {
System.err.println("请设置环境变量 DASHSCOPE_API_KEY");
return;
}
// 2. Initialize the Generation instance
// API keys are region-specific. Ensure baseUrl and the API key use the same region.
// For a Beijing model, set baseUrl to https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/api/v1
Generation gen = new Generation(Protocol.HTTP.getValue(), "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1");
CountDownLatch latch = new CountDownLatch(1);
// 3. Build request parameters
GenerationParam param = GenerationParam.builder()
.apiKey(apiKey)
.model("qwen-plus")
.messages(Arrays.asList(
Message.builder()
.role(Role.USER.getValue())
.content("介绍一下自己")
.build()
))
.resultFormat(GenerationParam.ResultFormat.MESSAGE)
.incrementalOutput(true) // Enable incremental output for streaming
.build();
// 4. Make a streaming call and handle the response
try {
Flowable<GenerationResult> result = gen.streamCall(param);
StringBuilder fullContent = new StringBuilder();
System.out.print("AI: ");
result
.subscribeOn(Schedulers.io()) // Execute request on IO thread
.observeOn(Schedulers.computation()) // Process response on computation thread
.subscribe(
// onNext: Handle each response fragment
message -> {
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
String finishReason = message.getOutput().getChoices().get(0).getFinishReason();
// Output content
System.out.print(content);
fullContent.append(content);
// When finishReason is not null, it indicates the last chunk. Output usage info.
if (finishReason != null && !"null".equals(finishReason)) {
System.out.println("\n--- 请求用量 ---");
System.out.println("输入 Tokens:" + message.getUsage().getInputTokens());
System.out.println("输出 Tokens:" + message.getUsage().getOutputTokens());
System.out.println("总 Tokens:" + message.getUsage().getTotalTokens());
}
System.out.flush(); // Flush output immediately
},
// onError: Handle errors
error -> {
System.err.println("\n请求失败: " + error.getMessage());
latch.countDown();
},
// onComplete: Completion callback
() -> {
System.out.println(); // New line
// System.out.println("Full response: " + fullContent.toString());
latch.countDown();
}
);
// Main thread waits for the async task to complete
latch.await();
System.out.println("程序执行完成");
} catch (Exception e) {
System.err.println("请求异常: " + e.getMessage());
e.printStackTrace();
}
}
}
Response
Copy
AI: 你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够帮助你回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时向我提问!
--- 请求用量 ---
输入 Tokens: 26
输出 Tokens: 91
总计 Tokens: 117
Request
Copy
# ======= Important notes =======
# Ensure the DASHSCOPE_API_KEY environment variable is set
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before running ===
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "system",
"content": "You are a helpful assistant."
},
{
"role": "user",
"content": "你是谁?"
}
]
},
"parameters": {
"result_format": "message",
"incremental_output":true
}
}'
Response
The response follows the Server-Sent Events (SSE) format. Each message includes:- id: Data chunk number.
- event: Event type, always "result".
- HTTP status code information.
- data: JSON-formatted data.
Copy
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"我是","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":27,"output_tokens":1,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"通义千","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":30,"output_tokens":4,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"问,阿里巴巴","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":33,"output_tokens":7,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
...
id:13
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"或需要帮助,欢迎随时","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":90,"output_tokens":64,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
id:14
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"告诉我!","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":92,"output_tokens":66,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
id:15
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":92,"output_tokens":66,"input_tokens":26,"prompt_tokens_details":{"cached_tokens":0}},"request_id":"d30a9914-ac97-9102-b746-ce0cb35e3fa2"}
Streaming output for multimodal models
Multimodal models support adding images, audio, and other content to conversations. Their streaming output implementation differs from text-only models in the following ways:- User message construction: Multimodal model inputs include not only text but also images, audio, and other multimodal information.
- DashScope SDK interface: Use the
client.multimodal.chat.createinterface in the DashScope Python SDK 2.0. Use the MultiModalConversation class in the DashScope Java SDK.
For multimodal models, see Image and video understanding, Text extraction, Audio understanding—Qwen3-Omni-Captioner, Kimi, etc. Qwen3.5-Omni and Qwen3-Omni-Flash support only streaming output. Their output can include text or audio and other multimodal content. Their result parsing differs from other models. For details, see Omni-modal.
- OpenAI compatible
- DashScope
Python
Copy
from openai import OpenAI
import os
client = OpenAI(
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# 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"),
# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
completion = client.chat.completions.create(
model="qwen3-vl-plus", # Replace with other multimodal models as needed and adjust messages accordingly
messages=[
{"role": "user",
"content": [{"type": "image_url",
"image_url": {"url": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},},
{"type": "text", "text": "图中描绘的是什么景象?"}]}],
stream=True,
# stream_options={"include_usage": True}
)
full_content = ""
print("流式输出内容为:")
for chunk in completion:
# If stream_options.include_usage is True, the last chunk's choices field is an empty list and should be skipped (token usage can be obtained via chunk.usage)
if chunk.choices and chunk.choices[0].delta.content != "":
full_content += chunk.choices[0].delta.content
print(chunk.choices[0].delta.content)
print(f"完整内容为:{full_content}")
Python
Copy
import os
import dashscope
# The following configuration is for the Singapore (ap-southeast-1) region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
# If you have not set an environment variable, replace the following line 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/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
messages = [
{
"role": "user",
"content": [
{"image": "https://dashscope.oss-cn-beijing.aliyuncs.com/images/dog_and_girl.jpeg"},
{"text": "图中描绘的是什么景象?"}
]
}
]
stream = client.multimodal.chat.create(
model='qwen3-vl-plus', # You can replace it with other multimodal models as needed and update the messages accordingly
messages=messages,
stream=True,
)
full_content = ""
print("流式输出内容为:")
for chunk in stream:
delta = chunk.choices[0].delta
if delta.content:
print(delta.content)
full_content += delta.content
print(f"完整内容为:{full_content}")
Streaming output for thinking models
Thinking models first returnreasoning_content (the thought process), then return content (the response). Determine whether the current stage is thinking or responding based on the data packet status.
For details on thinking models, see Deep thinking and Image and video understanding.
For streaming output implementation of Qwen3-Omni-Flash (thinking mode), see Omni-modal.
- OpenAI compatible
- DashScope
Below is the response format when calling the thinking mode of the qwen-plus model using the OpenAI Python SDK in streaming mode:
Copy
# 思考阶段
...
ChoiceDelta(content=None, function_call=None, refusal=None, role=None, tool_calls=None, reasoning_content='覆盖所有要点,同时')
ChoiceDelta(content=None, function_call=None, refusal=None, role=None, tool_calls=None, reasoning_content='自然流畅。')
# 回复阶段
ChoiceDelta(content='你好!我是**通', function_call=None, refusal=None, role=None, tool_calls=None, reasoning_content=None)
ChoiceDelta(content='义千问**(', function_call=None, refusal=None, role=None, tool_calls=None, reasoning_content=None)
...
- If
reasoning_contentis not None andcontentisNone, the current stage is thinking. - If
reasoning_contentis None andcontentis notNone, the current stage is responding. - If both are
None, the stage remains the same as the previous packet.
- Python
- Node.js
- HTTP
Example code
Copy
from openai import OpenAI
import os
# Initialize the OpenAI client
client = OpenAI(
# If the environment variable is unset, insert your Model Studio API key: api_key="sk-xxx"
api_key=os.getenv("DASHSCOPE_API_KEY"),
base_url="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1",
)
messages = [{"role": "user", "content": "你是谁"}]
completion = client.chat.completions.create(
model="qwen-plus", # Replace with other deep-thinking models as needed
messages=messages,
# The enable_thinking parameter enables the thinking process. This parameter has no effect on models QwQ.
extra_body={"enable_thinking": True},
stream=True,
# stream_options={
# "include_usage": True
# },
)
reasoning_content = "" # Full thought process
answer_content = "" # Full response
is_answering = False # Whether in the response stage
print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")
for chunk in completion:
if not chunk.choices:
print("\nUsage:")
print(chunk.usage)
continue
delta = chunk.choices[0].delta
# Collect only 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
# Received content, start responding
if hasattr(delta, "content") and delta.content:
if not is_answering:
print("\n" + "=" * 20 + "完整回复" + "=" * 20 + "\n")
is_answering = True
print(delta.content, end="", flush=True)
answer_content += delta.content
Response
Copy
====================思考过程====================
好的,用户问“你是谁”,我需要给出一个准确且友好的回答。首先,我要确认自己的身份,即通义千问,由阿里巴巴集团旗下的通义实验室研发。接下来,应该说明我的主要功能,比如回答问题、创作文字、逻辑推理等。同时,要保持语气亲切,避免过于技术化,让用户感觉轻松。还要注意不要使用复杂术语,确保回答简洁明了。另外,可能需要加入一些互动元素,邀请用户提问,促进进一步交流。最后,检查是否有遗漏的重要信息,比如我的中文名称“通义千问”和英文名称“Qwen”,以及所属公司和实验室。确保回答全面且符合用户期望。
====================完整回复====================
你好!我是通义千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以回答问题、创作文字、进行逻辑推理、编程等,旨在为用户提供高质量的信息和服务。你可以叫我Qwen,或者直接叫我通义千问。有什么我可以帮你的吗?
Example code
Copy
import OpenAI from "openai";
import process from 'process';
// Initialize the openai client
const openai = new OpenAI({
apiKey: process.env.DASHSCOPE_API_KEY, // Read from environment variable
baseURL: 'https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1'
});
let reasoningContent = '';
let answerContent = '';
let isAnswering = false;
async function main() {
try {
const messages = [{ role: 'user', content: '你是谁' }];
const stream = await openai.chat.completions.create({
// Replace with other Qwen3 models or QwQ models as needed
model: 'qwen-plus',
messages,
stream: true,
// The enable_thinking parameter enables the thinking process. This parameter has no effect on models QwQ.
enable_thinking: true
});
console.log('\n' + '='.repeat(20) + '思考过程' + '='.repeat(20) + '\n');
for await (const chunk of stream) {
if (!chunk.choices?.length) {
console.log('\nUsage:');
console.log(chunk.usage);
continue;
}
const delta = chunk.choices[0].delta;
// Collect only thinking content
if (delta.reasoning_content !== undefined && delta.reasoning_content !== null) {
if (!isAnswering) {
process.stdout.write(delta.reasoning_content);
}
reasoningContent += delta.reasoning_content;
}
// Received content, start responding
if (delta.content !== undefined && delta.content) {
if (!isAnswering) {
console.log('\n' + '='.repeat(20) + '完整回复' + '='.repeat(20) + '\n');
isAnswering = true;
}
process.stdout.write(delta.content);
answerContent += delta.content;
}
}
} catch (error) {
console.error('Error:', error);
}
}
main();
Response
Copy
====================思考过程====================
好的,用户问“你是谁”,我需要回答我的身份。首先,我应该明确说明我是通义千问,由阿里云开发的超大规模语言模型。接下来,可以提到我的主要功能,比如回答问题、创作文字、逻辑推理等。还要强调我的多语言支持,包括中文和英文,这样用户知道我可以处理不同语言的请求。另外,可能需要解释一下我的应用场景,比如学习、工作和生活中的帮助。不过用户的问题比较直接,可能不需要太详细的信息,保持简洁明了。同时,要确保语气友好,邀请用户进一步提问。检查有没有遗漏的重要信息,比如我的版本或最新更新,但可能用户不需要那么详细。最后,确认回答准确无误,没有错误信息。
====================完整回复====================
我是通义千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字、逻辑推理、编程等多种任务,支持中英文等多种语言。如果你有任何问题或需要帮,欢迎随时告诉我!
Example code
- curl
For Qwen3 open-source models, set
enable_thinking to true to enable thinking mode. The enable_thinking parameter has no effect on models QwQ .Copy
curl -X POST https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/compatible-mode/v1/chat/completions \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-d '{
"model": "qwen-plus",
"messages": [
{
"role": "user",
"content": "你是谁"
}
],
"stream": true,
"stream_options": {
"include_usage": true
},
"enable_thinking": true
}'
Response
Copy
data: {"choices":[{"delta":{"content":null,"role":"assistant","reasoning_content":""},"index":0,"logprobs":null,"finish_reason":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
.....
data: {"choices":[{"finish_reason":"stop","delta":{"content":"","reasoning_content":null},"index":0,"logprobs":null}],"object":"chat.completion.chunk","usage":null,"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: {"choices":[],"object":"chat.completion.chunk","usage":{"prompt_tokens":10,"completion_tokens":360,"total_tokens":370},"created":1745485391,"system_fingerprint":null,"model":"qwen-plus","id":"chatcmpl-e2edaf2c-8aaf-9e54-90e2-b21dd5045503"}
data: [DONE]
Below is the streaming response format when calling the thinking mode of the qwen-plus model using the DashScope Python SDK:
Copy
# 思考阶段
...
{"role": "assistant", "content": "", "reasoning_content": "信息量大,"}
{"role": "assistant", "content": "", "reasoning_content": "让用户觉得有帮助。"}
# 回复阶段
{"role": "assistant", "content": "我是通义千问", "reasoning_content": ""}
{"role": "assistant", "content": ",由通义实验室研发", "reasoning_content": ""}
...
- If
reasoning_contentis not "", andcontentis "", the current stage is thinking. - If
reasoning_contentis "", andcontentis not "", the current stage is responding. - If both are "", the stage remains the same as the previous packet.
- Python
- Java
- HTTP
Example code
Copy
import os
import dashscope
# The following configuration is for the Singapore (ap-southeast-1) region. Replace {WorkspaceId} with your actual workspace ID. The region value varies by region.
client = dashscope.Client(
# If you have not set an environment variable, replace the following line 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/model-studio/get-api-key
api_key=os.getenv("DASHSCOPE_API_KEY"),
workspace="{WorkspaceId}",
region="ap-southeast-1",
)
messages = [{"role": "user", "content": "你是谁?"}]
stream = client.chat.completions.create(
# You can replace it with other deep thinking models as needed
model="qwen-plus",
messages=messages,
# Enable deep thinking; this parameter has no effect on QwQ and DeepSeek-R1 models
enable_thinking=True,
stream=True, # Streaming output is incremental by default (Qwen3 open-source models support incremental output only; incremental output is also recommended for other models for a better experience)
)
# Define the complete thinking process
reasoning_content = ""
# Define the complete response
answer_content = ""
# Determine whether the thinking process has ended and the response has started
is_answering = False
print("=" * 20 + "思考过程" + "=" * 20)
for chunk in stream:
# If both the thinking process and the response are empty, ignore
if (
chunk.choices[0].delta.content == ""
and chunk.choices[0].delta.reasoning_content == ""
):
pass
else:
# If it is currently the thinking process
if (
chunk.choices[0].delta.reasoning_content != ""
and chunk.choices[0].delta.content == ""
):
print(chunk.choices[0].delta.reasoning_content, end="", flush=True)
reasoning_content += chunk.choices[0].delta.reasoning_content
# If it is currently the response
elif chunk.choices[0].delta.content != "":
if not is_answering:
print("\n" + "=" * 20 + "完整回复" + "=" * 20)
is_answering = True
print(chunk.choices[0].delta.content, end="", flush=True)
answer_content += chunk.choices[0].delta.content
# To print the complete thinking process and complete response, uncomment and run the following code
# print("=" * 20 + "Full thought process" + "=" * 20 + "\n")
# print(f"{reasoning_content}")
# print("=" * 20 + "Full response" + "=" * 20 + "\n")
# print(f"{answer_content}")
Response
Copy
====================思考过程====================
好的,用户问:“你是谁?”我需要回答这个问题。首先,我要明确自己的身份,即通义千问,由阿里云开发的超大规模语言模型。接下来,要说明我的功能和用途,比如回答问题、创作文字、逻辑推理等。同时,要强调我的目标是成为用户的得力助手,提供帮助和支持。
在表达时,要保持口语化,避免使用专业术语或复杂句式。可以加入一些亲切的语气词,比如“你好呀~”,让对话更自然。另外,要确保信息准确,不遗漏关键点,比如我的开发者、主要功能和使用场景。
还要考虑用户可能的后续问题,比如具体的应用例子或技术细节,所以在回答中可以适当埋下伏笔,引导用户进一步提问。例如,提到“无论是日常生活的疑问还是专业领域的问题,我都能尽力提供帮助”,这样既全面又开放。
最后,检查回答是否流畅,有没有重复或冗余的信息,确保简洁明了。同时,保持友好和专业的平衡,让用户感受到既亲切又可靠。
====================完整回复====================
你好呀~我是通义千问,是阿里云开发的一款超大规模语言模型。我能够回答问题、创作文字、进行逻辑推理、编程等等,旨在为用户提供帮助和支持。无论是日常生活的疑问还是专业领域的问题,我都能尽力提供帮助。有什么我可以帮你的吗?
Example code
Copy
// dashscope SDK version >= 2.19.4
import java.util.Arrays;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.alibaba.dashscope.aigc.generation.Generation;
import com.alibaba.dashscope.aigc.generation.GenerationParam;
import com.alibaba.dashscope.aigc.generation.GenerationResult;
import com.alibaba.dashscope.common.Message;
import com.alibaba.dashscope.common.Role;
import com.alibaba.dashscope.exception.ApiException;
import com.alibaba.dashscope.exception.InputRequiredException;
import com.alibaba.dashscope.exception.NoApiKeyException;
import io.reactivex.Flowable;
import java.lang.System;
import com.alibaba.dashscope.utils.Constants;
public class Main {
static {
Constants.baseHttpApiUrl="https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1";
}
private static final Logger logger = LoggerFactory.getLogger(Main.class);
private static StringBuilder reasoningContent = new StringBuilder();
private static StringBuilder finalContent = new StringBuilder();
private static boolean isFirstPrint = true;
private static void handleGenerationResult(GenerationResult message) {
String reasoning = message.getOutput().getChoices().get(0).getMessage().getReasoningContent();
String content = message.getOutput().getChoices().get(0).getMessage().getContent();
if (!reasoning.isEmpty()) {
reasoningContent.append(reasoning);
if (isFirstPrint) {
System.out.println("====================思考过程====================");
isFirstPrint = false;
}
System.out.print(reasoning);
}
if (!content.isEmpty()) {
finalContent.append(content);
if (!isFirstPrint) {
System.out.println("\n====================完整回复====================");
isFirstPrint = true;
}
System.out.print(content);
}
}
private static GenerationParam buildGenerationParam(Message userMsg) {
return GenerationParam.builder()
// If you haven't configured an environment variable, replace the next line with your Alibaba Cloud Model Studio API key: .apiKey("sk-xxx")
.apiKey(System.getenv("DASHSCOPE_API_KEY"))
.model("qwen-plus")
.enableThinking(true)
.incrementalOutput(true)
.resultFormat("message")
.messages(Arrays.asList(userMsg))
.build();
}
public static void streamCallWithMessage(Generation gen, Message userMsg)
throws NoApiKeyException, ApiException, InputRequiredException {
GenerationParam param = buildGenerationParam(userMsg);
Flowable<GenerationResult> result = gen.streamCall(param);
result.blockingForEach(message -> handleGenerationResult(message));
}
public static void main(String[] args) {
try {
Generation gen = new Generation();
Message userMsg = Message.builder().role(Role.USER.getValue()).content("你是谁?").build();
streamCallWithMessage(gen, userMsg);
// Print final result
// if (reasoningContent.length() > 0) {
// System.out.println("\n====================Full response====================");
// System.out.println(finalContent.toString());
// }
} catch (ApiException | NoApiKeyException | InputRequiredException e) {
logger.error("An exception occurred: {}", e.getMessage());
}
System.exit(0);
}
}
Response
Copy
====================思考过程====================
好的,用户问“你是谁?”,我需要根据之前的设定来回答。首先,我的角色是通义千问,阿里巴巴集团旗下的超大规模语言模型。要保持口语化,简洁易懂。
用户可能刚接触我,或者想确认我的身份。应该先直接回答我是谁,然后简要说明我的功能和用途,比如回答问题、创作文字、编程等。还要提到支持多语言,这样用户知道我可以处理不同语言的需求。
另外,根据指导方针,要保持拟人性,所以语气要友好,可能用表情符号增加亲切感。同时,可能需要引导用户进一步提问或使用我的功能,比如问他们需要什么帮助。
需要注意不要使用复杂术语,避免冗长。检查是否有遗漏的关键点,比如多语言支持和具体能力。确保回答符合所有要求,包括口语化和简洁。
====================完整回复====================
你好!我是通义千问,阿里巴巴集团旗下的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我熟练掌握多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。有什么需要我帮忙的吗?
Example code
- curl
For hybrid thinking models, set
enable_thinking to true to enable thinking mode. The enable_thinking parameter has no effect on models QwQ .Copy
# ======= Important notes =======
# API keys differ by region. Get an API key: https://www.alibabacloud.com/help/model-studio/get-api-key
# Singapore region URL. Replace {WorkspaceId} with your actual workspace ID. URLs vary by region.
# === Delete this comment before running ===
curl -X POST "https://{WorkspaceId}.ap-southeast-1.maas.aliyuncs.com/api/v1/services/aigc/text-generation/generation" \
-H "Authorization: Bearer $DASHSCOPE_API_KEY" \
-H "Content-Type: application/json" \
-H "X-DashScope-SSE: enable" \
-d '{
"model": "qwen-plus",
"input":{
"messages":[
{
"role": "user",
"content": "你是谁?"
}
]
},
"parameters":{
"enable_thinking": true,
"incremental_output": true,
"result_format": "message"
}
}'
Response
Copy
id:1
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"嗯","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":14,"input_tokens":11,"output_tokens":3},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:2
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":",","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":15,"input_tokens":11,"output_tokens":4},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:3
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"用户","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":16,"input_tokens":11,"output_tokens":5},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:4
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"问","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":17,"input_tokens":11,"output_tokens":6},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:5
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"“","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":18,"input_tokens":11,"output_tokens":7},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
......
id:358
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"帮助","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":373,"input_tokens":11,"output_tokens":362},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:359
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":",","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":374,"input_tokens":11,"output_tokens":363},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:360
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"欢迎","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":375,"input_tokens":11,"output_tokens":364},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:361
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"随时","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":376,"input_tokens":11,"output_tokens":365},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:362
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"告诉我","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":377,"input_tokens":11,"output_tokens":366},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:363
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"!","reasoning_content":"","role":"assistant"},"finish_reason":"null"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
id:364
event:result
:HTTP_STATUS/200
data:{"output":{"choices":[{"message":{"content":"","reasoning_content":"","role":"assistant"},"finish_reason":"stop"}]},"usage":{"total_tokens":378,"input_tokens":11,"output_tokens":367},"request_id":"25d58c29-c47b-9e8d-a0f1-d6c309ec58b1"}
Going live
- Performance and resource management: In backend services, maintaining an HTTP persistent connection for each streaming request consumes resources. Configure your service with appropriate connection pool size and timeout values. In high concurrency scenarios, monitor file descriptor usage to prevent exhaustion.
-
Client-side rendering: On web frontends, use the
ReadableStreamandTextDecoderStreamAPIs to smoothly handle and render SSE event streams, delivering the best user experience. -
Model monitoring:
- Key metrics: Monitor Time to First Token (TTFT), the core metric for streaming experience. Also monitor API error rate and average response time.
- Alerting: Set alerts for abnormal API error rates, especially 4xx and 5xx errors.
-
Nginx proxy configuration: If using Nginx as a reverse proxy, its default output buffering (proxy_buffering) breaks the real-time nature of streaming responses. To ensure data is pushed to clients immediately, disable this feature by setting
proxy_buffering offin your Nginx configuration file.
Error codes
If the model call fails and returns an error message, see Error codes for resolution.FAQ
Q: Why is there no usage information in the response?
A: The OpenAI protocol does not return usage information by default. Set thestream_options parameter to include usage information in the final returned packet.
Q: Does enabling streaming output affect the model's response quality?
A: No. However, some models support only streaming output, and non-streaming calls might cause timeout errors. We recommend using streaming output.Q: What is the difference between non-streaming and streaming calls?
A: Key differences:- Timeout limit: For non-streaming calls, the maximum timeout is at least 300 seconds and varies by region and model. If not completed in time, the request is terminated.
- Output structure: Non-streaming calls return the complete response (a single JSON object) at once. Streaming calls return data chunks progressively via the SSE protocol, with each chunk containing part of the generated content. The client must assemble these chunks.
- Feature compatibility: Both support features like JSON Mode and Function Call with no functional differences.
Q: Does streaming output support JSON Mode (structured output)?
A: Yes. Setstream to true and response_format to {"type": "json_object"} in the request. The model will return JSON-formatted content fragments progressively. The final assembled output will be valid JSON.