> ## Documentation Index
> Fetch the complete documentation index at: https://docs.moxus.cloud/llms.txt
> Use this file to discover all available pages before exploring further.

# 流式输出

> 流式输出（Streaming）使模型的响应以增量方式逐步返回，而非等待全部生成完成后一次性返回。这可显著提升用户体验，并常用于长响应场景。

流式输出（Streaming）使模型的响应以增量方式逐步返回，而非等待全部生成完成后一次性返回。这可显著提升用户体验，并常用于长响应场景。

## 启用方式

在请求体中设置 `"stream": true`：

```json theme={null}
{
  "model": "gpt-5.4-mini",
  "messages": [{"role": "user", "content": "写一首关于春天的诗"}],
  "stream": true
}
```

## 流式响应格式

启用流式后，服务器通过 Server-Sent Events（SSE）持续推送数据块（chunk），每块以 `data: ` 开头：

```text theme={null}
data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"role":"assistant","content":""},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"春"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"风"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{"content":"拂面"},"finish_reason":null}]}

data: {"id":"chatcmpl-xxx","object":"chat.completion.chunk","choices":[{"index":0,"delta":{},"finish_reason":"stop"}]}

data: [DONE]
```

关键点：

* 每个 chunk 的增量文本位于 `choices[0].delta.content`。
* 将所有 `delta.content` 按顺序拼接，即为完整响应。
* 最后一个有效 chunk 的 `finish_reason` 变为 `stop`（正常结束）。
* 流以 `data: [DONE]` 标志结束。

## cURL 示例

`-N` 会关闭 cURL 的输出缓冲，使每个 SSE 数据块到达后立即显示。将命令中的 `你的密钥` 替换为实际密钥即可执行。

```bash theme={null}
curl -N https://moxus.cloud/v1/chat/completions \
  -H "Authorization: Bearer 你的密钥" \
  -H "Content-Type: application/json" \
  -d '{
    "model": "gpt-5.4-mini",
    "messages": [{"role": "user", "content": "写一首关于春天的短诗"}],
    "stream": true
  }'
```

## Python 示例

使用官方 SDK 时，流式处理非常简单，遍历返回的迭代器即可。将 `API_KEY` 中的 `你的密钥` 替换为实际密钥：

```python theme={null}
import httpx
from openai import OpenAI

API_KEY = "你的密钥"

client = OpenAI(
    api_key=API_KEY,
    base_url="https://moxus.cloud/v1",
    # 直接连接 Moxus AI，不读取系统或终端代理环境变量。
    http_client=httpx.Client(trust_env=False, timeout=60.0),
)

for chunk in client.chat.completions.create(
    model="gpt-5.4-mini",
    messages=[{"role": "user", "content": "写一首关于春天的短诗"}],
    stream=True,
    # 可选：让流结束时返回本次 Token 用量；不需要或模型不支持时删除 stream_options 行。
    stream_options={"include_usage": True},
):
    if chunk.usage:
        print(f"\n用量：{chunk.usage}")
    if not chunk.choices:
        continue
    delta = chunk.choices[0].delta.content or ""
    print(delta, end="", flush=True)

print()
```

## Node.js 示例

将 `API_KEY` 中的 `你的密钥` 替换为实际密钥：

```javascript theme={null}
import OpenAI from "openai";

const API_KEY = "你的密钥";

const client = new OpenAI({
  apiKey: API_KEY,
  baseURL: "https://moxus.cloud/v1",
});

const stream = await client.chat.completions.create({
  model: "gpt-5.4-mini",
  messages: [{ role: "user", content: "写一首关于春天的短诗" }],
  stream: true,
  // 可选：让流结束时返回本次 Token 用量；不需要或模型不支持时删除 stream_options 行。
  stream_options: { include_usage: true },
});

for await (const chunk of stream) {
  if (chunk.usage) {
    console.log("\n用量：", chunk.usage);
  }
  const delta = chunk.choices[0]?.delta?.content || "";
  process.stdout.write(delta);
}
```

## 适用场景

| 场景               | 建议               |
| ---------------- | ---------------- |
| 聊天界面或交互式应用       | 推荐，用户体验更佳        |
| 长文生成（文章、报告）      | 推荐，边生成边展示        |
| 后台批处理或仅需最终结果     | 使用非流式更简单         |
| 需对完整结果进行 JSON 解析 | 可使用流式，但须先拼接完整再解析 |

## 常见问题

**流式与非流式的价格是否相同？**
相同。计费仅与输入、输出 Token 数有关，与是否流式无关。

**为何无法获取 `usage`？**
默认流式不返回 usage，需设置 `stream_options.include_usage`（且模型需支持）。

**是否可中途停止？**
可以。客户端断开连接即可停止接收，已生成的部分仍会计费。

## 后续步骤

* 调用工具：参阅 [函数调用](/zh/guide/function-calling)。
* 约束返回 JSON：参阅 [结构化输出](/zh/guide/structured-output)。
