Skip to main content

Streaming output

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 stream to true.
  • 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
import os
from openai import OpenAI

# 1. 准备工作:初始化客户端
client = OpenAI(
    # 建议通过环境变量配置API Key,避免硬编码。
    api_key=os.environ["DASHSCOPE_API_KEY"],
    # API Key与地域强绑定,请确保base_url与API Key的地域一致。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

# 2. 发起流式请求
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. 处理流式响应
# 用列表暂存响应片段,最后 join 比逐次 += 字符串更高效
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--- 完整回复 ---\n{full_response}")

Response

AI: 你好!我是Qwen,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我能够回答问题、创作文字,比如写故事、写公文、写邮件、写剧本、逻辑推理、编程等等,还能表达观点,玩游戏等。我支持多种语言,包括但不限于中文、英文、德语、法语、西班牙语等。如果你有任何问题或需要帮助,欢迎随时告诉我!
--- 请求用量 ---
输入 Tokens: 26
输出 Tokens: 87
总计 Tokens: 113

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.create interface in DashScope Python SDK 2.0. Use the MultiModalConversation class in the DashScope Java SDK.
For multimodal models, see Image and video understanding, Text extraction, Interface interaction, 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
from openai import OpenAI
import os

client = OpenAI(
    # 若没有配置环境变量,请用百炼API Key将下行替换为:api_key="sk-xxx"
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),

    # 以下为华北2(北京)地域的URL,调用时请将WorkspaceId替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

completion = client.chat.completions.create(
    model="qwen3-vl-plus",  # 可按需更换为其它多模态模型,并修改相应的 messages
    messages=[
        {"role": "user",
         "content": [{"type": "image_url",
                    "image_url": {"url": "https://help-static-aliyun-doc.aliyuncs.com/file-manage-files/zh-CN/20241022/emyrja/dog_and_girl.jpeg"},},
                    {"type": "text", "text": "图中描绘的是什么景象?"}]}],
    stream=True,
  # stream_options={"include_usage": True}
)
full_content = ""
print("流式输出内容为:")
for chunk in completion:
    # 如果stream_options.include_usage为True,则最后一个chunk的choices字段为空列表,需要跳过(可以通过chunk.usage获取 Token 使用量)
    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}")

Streaming output for thinking models

Thinking models first return reasoning_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:
# 思考阶段
...
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_content is not None and content is None, the current stage is thinking.
  • If reasoning_content is None and content is not None, the current stage is responding.
  • If both are None, the stage remains the same as the previous packet.
  • Python
  • Node.js
  • HTTP

Example code

from openai import OpenAI
import os

# 初始化OpenAI客户端
client = OpenAI(
    # 如果没有配置环境变量,请用阿里云百炼API Key替换:api_key="sk-xxx"
    # 各地域的API Key不同。获取API Key:https://help.aliyun.com/zh/model-studio/get-api-key
    api_key=os.getenv("DASHSCOPE_API_KEY"),
    # 以下为华北2(北京)地域的URL,调用时请将WorkspaceId替换为真实的业务空间ID,各地域的URL不同。
    base_url="https://{WorkspaceId}.cn-beijing.maas.aliyuncs.com/compatible-mode/v1",
)

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

completion = client.chat.completions.create(
    model="qwen-plus",  # 您可以按需更换为其它深度思考模型
    messages=messages,
    # enable_thinking 参数开启思考过程,QwQ 与 DeepSeek-R1 模型总会进行思考,不支持该参数
    extra_body={"enable_thinking": True},
    stream=True,
    # stream_options={
    #     "include_usage": True
    # },
)

reasoning_content = ""  # 完整思考过程
answer_content = ""  # 完整回复
is_answering = False  # 是否进入回复阶段
print("\n" + "=" * 20 + "思考过程" + "=" * 20 + "\n")

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

    delta = chunk.choices[0].delta

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

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

Response

====================思考过程====================

好的,用户问“你是谁”,我需要给出一个准确且友好的回答。首先,我要确认自己的身份,即通义千问,由阿里巴巴集团旗下的通义实验室研发。接下来,应该说明我的主要功能,比如回答问题、创作文字、逻辑推理等。同时,要保持语气亲切,避免过于技术化,让用户感觉轻松。还要注意不要使用复杂术语,确保回答简洁明了。另外,可能需要加入一些互动元素,邀请用户提问,促进进一步交流。最后,检查是否有遗漏的重要信息,比如我的中文名称“通义千问”和英文名称“Qwen”,以及所属公司和实验室。确保回答全面且符合用户期望。
====================完整回复====================

你好!我是通义千问,是阿里巴巴集团旗下的通义实验室自主研发的超大规模语言模型。我可以回答问题、创作文字、进行逻辑推理、编程等,旨在为用户提供高质量的信息和服务。你可以叫我Qwen,或者直接叫我通义千问。有什么我可以帮你的吗?

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 ReadableStream and TextDecoderStream APIs 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 off in 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 the stream_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.
We recommend using streaming output to avoid timeouts and improve user experience.

Q: Does streaming output support JSON Mode (structured output)?

A: Yes. Set stream 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.