# 串流 (/zh-Hant/docs/concepts/streaming)

透過 server-sent events 在 token 生成的同時接收。



設定 `"stream": true`，回應就會以 [server-sent events](https://developer.mozilla.org/docs/Web/API/Server-sent_events) 送達，而不是單一的 JSON 主體。各格式保有自己的事件結構：

| 端點                     | 串流格式                                                              |
| ---------------------- | ----------------------------------------------------------------- |
| `/v1/chat/completions` | 由 `chat.completion.chunk` 物件組成的 `data:` 行，以 `data: [DONE]` 結尾     |
| `/v1/responses`        | 具型別的事件，例如 `response.output_text.delta` 與 `response.completed`     |
| `/v1/messages`         | Anthropic 事件：`message_start`、`content_block_delta`、`message_stop` |

## 串流中的 token 用量 [#串流中的-token-用量]

Chat completions 請加上 `"stream_options": { "include_usage": true }`，即可在最後一個 chunk 取得 token 數。Responses 與 Messages 的串流會在結尾事件中回報用量。

## 範例 [#範例]

<Tabs items="[&#x22;Python&#x22;, &#x22;TypeScript&#x22;]">
  <Tab value="Python">
    ```python
    stream = client.chat.completions.create(
        model="deepseek-v4-1-flash",
        messages=[{"role": "user", "content": "Write a haiku about rivers."}],
        stream=True,
    )
    for chunk in stream:
        if chunk.choices and chunk.choices[0].delta.content:
            print(chunk.choices[0].delta.content, end="", flush=True)
    ```
  </Tab>

  <Tab value="TypeScript">
    ```ts
    const stream = await client.chat.completions.create({
      model: "deepseek-v4-1-flash",
      messages: [{ role: "user", content: "Write a haiku about rivers." }],
      stream: true,
    });
    for await (const chunk of stream) {
      process.stdout.write(chunk.choices[0]?.delta?.content ?? "");
    }
    ```
  </Tab>
</Tabs>
